Descending Numbers with Diagonal Asterisk in C

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Conditional Print

What You’ll Learn

The descending number pattern with diagonal asterisk prints 5432*, 543*1, 54*21, 5*321, *4321 — a natural step after the bidirectional triangle in Program 25. This tutorial covers descending digits, the i == j condition, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

Diagonal star

Each row prints descending digits with one * where i == j — the star moves left each row.

Outer Loop

i = 1..n

for (i = 1; i <= n; i++) walks each row top to bottom.

Descending Inner Loop

j = n..1

for (j = n; j >= 1; j--) prints digits 5, 4, 3, 2, 1 per row.

Diagonal Condition

i == j

When i == j, print *; otherwise print j.

Live Preview

3–9 size

Pick a size n and draw the diagonal asterisk pattern instantly in the browser.

O(n²)

Complexity

Each row prints n characters; total work scales as .

Introduction

A descending number pattern with diagonal asterisk prints digits from n down to 1 on each row, replacing one position with * where i == j. With n = 5, the output is 5432*, 543*1, 54*21, 5*321, *4321.

In C you use an outer loop for rows, a descending inner loop for columns, and an if (i == j) to swap a digit for a star.

Why it matters?

It combines row/column indexing with a conditional swap — a step up from Program 25’s digit mapping.

Key Highlights

Descending j

j = n..1 — digits decrease left to right.

Diagonal star

i == j marks the star position.

Moving star

As i grows, the star shifts left each row.

Series Foundation

Follow Program 25; continue to Program 27 (palindrome triangle) next.

In short: for each i, scan j from n down to 1 — print * when i == j, else print j, then printf("\n").

📝 Problem & Approach

Given a positive integer n (e.g. 5), print n rows of descending digits with one diagonal * per row where i == j.

c
// n = 5 (conceptual shape)
// 5432*
// 543*1
// 54*21
// 5*321
// *4321

Inputs & Outputs

ItemTypeDescription
nintPattern size — outer loop runs from 1 to n.
iintOuter loop — current row number; also the diagonal star column.
jintInner loop — descending column digit from n down to 1.
Outputchar* when i == j; otherwise the digit j.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from n down to 1:
        if i == j:
            print "*"
        else:
            print j
    print newline

Approach comparison

ApproachIdeaBest for
if (i == j)5432*, 543*1, …Learning and interviews
Custom symbolReplace * with # or any charVisual variants
User-input nscanf("%d", &n);Flexible console programs

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= n; i++)
Descending columnsfor (j = n; j >= 1; j--)
Diagonal starif (i == j) printf("*");
Otherwise digitelse printf("%d", j);
End the rowprintf("\n");
User inputscanf("%d", &n);

📋 Fixed n vs Custom Symbol vs User Input

Same diagonal asterisk pattern — different ways to control size and the replacement character.

Outer loop
i = 1..n

Row index doubles as star column

Inner loop
j = n..1

Descending digits per row

Condition
i == j

Swap digit for star on diagonal

Learning tip
if/else

One inner loop handles star vs digit

Context

When This Pattern Shows Up

Reach for this pattern when teaching row/column indexing, conditional character substitution, and diagonal effects in nested loops.

  1. Post triangle exercise

    Natural follow-up after Program 25 — introduces i == j diagonal substitution.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with scanf for a flexible row count.

  4. Gateway to variants

    Compare Program 25 (bidirectional triangle) and Program 27 (palindrome triangle) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a size between 3 and 9 and draw the descending diagonal asterisk pattern in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C programs — fixed size, custom symbol, and user input. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the diagonal asterisk pattern with i == j.

Example 1 — Fixed n = 5

Hard-coded size — ideal for first demos and screenshots.

c
#include <stdio.h>

int main() {
    int i, j;

    for (i = 1; i <= 5; ++i) {
        for (j = 5; j >= 1; --j) {
            if (i == j)
                printf("*");
            else
                printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}

How It Works

When i = 1, the star lands at j = 1 (rightmost) — output 5432*. When i = 5, the star is at the leftmost position — output *4321. Each row always prints n characters.

📈 Custom Symbol

Replace the diagonal asterisk with another character like #.

Example 2 — Custom Symbol #

Keep n = 5 but use hash instead of asterisk on the diagonal.

c
#include <stdio.h>

int main() {
    int n = 5;
    int i, j;

    for (i = 1; i <= n; ++i) {
        for (j = n; j >= 1; --j) {
            if (i == j)
                printf("#");
            else
                printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}

How It Works

Only the replacement character changes — "#" instead of "*". Loop bounds and the i == j condition stay the same as Example 1.

⚡ User Input

Read the pattern size with scanf instead of hard-coding 5.

Example 3 — User Input

Read n with scanf("%d", &n); both loops use n as the bound.

c
#include <stdio.h>

int main() {
    int n;
    int i, j;

    printf("Enter size: ");
    scanf("%d", &n);

    for (i = 1; i <= n; ++i) {
        for (j = n; j >= 1; --j) {
            if (i == j)
                printf("*");
            else
                printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}

How It Works

Same i == j core as Example 1; only the source of n changes. The diagonal star scales with the user’s input. Non-numeric input leaves n unset if you ignore scanf’s return value — always check it in safer labs.

🧠 How the Algorithm Prints Rows

1

Set up

#include <stdio.h> brings in printf / scanf. Set loop variables i, j and n = 5.

Setup
2

Outer loop walks rows

for (i = 1; i <= n; i++) — row index also marks the star column.

Row
3

Descending inner loop (j)

for (j = n; j >= 1; j--) — prints digits n..1 per row.

Columns
4

Diagonal substitution

if (i == j) prints *; else printf("%d", j).

if/else
5

New line

printf("\n") ends the row after the inner loop.

Break
=

Diagonal asterisk complete

Star moves left each row — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — n = 5

Trace each outer-loop value of i, where i == j, and the full row output.

iStar at jDigits printedRow output
1j = 15, 4, 3, 2, *5432*
2j = 25, 4, 3, *, 1543*1
3j = 35, 4, *, 2, 154*21
4j = 45, *, 3, 2, 15*321
5j = 5*, 4, 3, 2, 1*4321

The star position moves left as i increases — each row still prints exactly n characters.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j = n..1 to j = 1..n and watch digit order flip.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: use i + j == n + 1 for the anti-diagonal star.

3. Console Formatting Drills

Practice Write vs printf("\n") without complex math.

Example: put printf("\n") inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters or add spaces once the loop works.

Example: replace * with # or a space character.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed chars for n = 5 → 5 × 5 = 25.

6. Input Validation Labs

Pair the pattern with scanf return checks and positive-row checks.

Example: reject max <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i and j on paper for n = 3 before coding — the star column is where they meet.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Do not print i in the else branch — use j for the descending digit.

  2. 2. Prefer scanf

    Check the return value so bad input does not leave n uninitialized.

  3. 3. Keep printf("\n") Outside

    Only call printf("\n") after the inner loop finishes the row.

  4. 4. Trace i and j on Paper

    Mark where i == j on each row before coding.

  5. 5. Dry-Run One Small n

    Trace n = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put printf("\n") inside the inner loop.

Common Pitfalls

Mistakes that commonly break diagonal asterisk patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use printf("*") or printf("%d", j); printf("\n") only after the inner loop.

  2. 2. Using i != j Instead of i == j

    Flipping the condition prints stars everywhere except the diagonal.

    → Print * when i == j, not when they differ.

  3. 3. Ascending Inner Loop

    Using j = 1..n reverses the digit order on each row.

    → Use for (j = n; j >= 1; j--) for descending digits.

  4. 4. Printing i Instead of j

    Writing printf("%d", i) in the else branch repeats the row number, not the column digit.

    → Print j in the else branch — it holds the descending column value.

  5. 5. Unchecked scanf

    Letters or empty input leave n uninitialized.

    → Check scanf return value and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single row

Output is just * — one star, one row.

n = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

n < 0

Treat as invalid; re-prompt instead of silent empty output.

n = 2

Smallest diagonal

Two rows: 2* and *1.

Bad input

Non-numeric scanf input

Unchecked scanf leaves n unset — check the return value.

Large n

Large size

Output grows as n² characters — fine for labs, noisy for huge n.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Bidirectional triangle

  • Shrinking rows with digit mapping
  • Review Program 25

2. Palindrome triangle

  • Symmetric rows with two inner loops
  • Continue with Program 27

3. Anti-diagonal star

  • Use i + j == n + 1 instead of i == j
  • Compare star position on each row

4. Multiple diagonals

  • Print * when i == j or i + j == n + 1
  • Harder follow-up after this page

Notes

  • Diagonal rule. When i == j, print *; otherwise print descending digit j.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints a single *.
  • Any single character works as the diagonal replacement — #, X, or a space.

Quick Takeaway: outer loop i = 1..n, descending inner loop j = n..1, print * when i == j else j, then printf("\n").

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1 & 3)O(n²)O(1)
Custom symbol (Example 2)O(n²)O(1)
Wrap Up

🎉 Conclusion

The descending number pattern with diagonal asterisk is a compact lesson in row/column indexing: print descending j values and swap one position with * when i == j. Master the fixed-n version, then try a custom symbol and user input.

Practice the three examples above, then continue to Program 27 for the palindrome number triangle.

Print j in the else branch, not i — validate n when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= n; i++) in the outer loop
  • Descend with for (j = n; j >= 1; j--)
  • Print * when i == j, else print j
  • Check scanf return value before using n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside the inner loop
  • Print i instead of j in the else branch
  • Flip the condition to i != j
  • Use ascending j unless you want reversed digits
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this diagonal pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

j = n..1

Descending

Code
+ 03

if/else

* or j

Code
04

Moving star

Left each row

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Because i increases from 1 to n while j decreases from n to 1. The condition i == j becomes true at a different position each row.
j holds the descending column digit (5, 4, 3, 2, 1). When i != j, print that digit to fill the row.
Yes. Replace printf("*") with any character or string — see Example 2 with #.
printf("%d", j) prints each digit or star on the same line. printf("\n") ends the row after the inner loop finishes.
j runs from n down to 1 so each row prints digits in descending order with the star at position i.
Replace 5 with n in both loops — see Example 3 and the live preview.
O(n²) for n rows because each row prints n characters using a nested loop.
Check scanf's return value: if (scanf("%d", &n) != 1) handle bad input. Unchecked scanf leaves n uninitialized on failure.
Only one row prints — a single *.

Did you Know? 🔊

This pattern prints descending numbers from n to 1 on each row. When the row index equals the current column value (i == j), it prints * instead of the number, creating a diagonal asterisk that moves left each row.

Continue to Program 27

Move on to the palindrome number triangle in the C number-pattern series.

Program 27 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful