Right-Aligned Descending Number Triangle in C

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Condition + Loops

What You’ll Learn

The right-aligned descending triangle prints 1, 21, 321, 4321, 54321 — a natural step after the spaced mirror in Program 29. This tutorial covers fixed-width loops, leading-space padding, conditional printing, a live preview, worked C examples, edge cases, and complexity.

Shape Rule

Spaces + digits

Each row prints leading spaces while j > i, then digits i..1 in descending order.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) — one right-aligned row per iteration.

Inner Loop (j)

rows..1

if (j > i) prints space; else prints j.

Fixed Width

Always rows

Inner loop always runs rows times — spaces pad the left side.

Live Preview

3–9 rows

Pick a row count and draw the right-aligned triangle in the browser.

O(n²)

Complexity

Each row runs one loop of width rows — total work scales as .

Introduction

A right-aligned descending number triangle prints leading spaces on each row, then digits from i down to 1. With rows = 5, the triangle grows rightward: 1, 21, … 54321.

In C you use one fixed-width inner loop: print a space when j > i, otherwise print j.

Why it matters?

It combines conditional printing with leading-space padding — a step up from Program 29’s two-loop mirror.

Key Highlights

Fixed width

Inner loop always runs rows times.

j > i

Print space for leading padding.

j <= i

Print digit in descending order.

Series Foundation

Follow Program 29; continue to Program 31 (number-star diamond) next.

In short: for each i, inner loop prints space or j, then printf("\n").

📝 Problem & Approach

Given rows = 5, print a right-aligned descending triangle: for each i, print spaces while j > i, then print digits i..1 in a fixed-width inner loop.

c
// rows = 5 (conceptual shape)
//     1
//    21
//   321
//  4321
// 54321

Inputs & Outputs

ItemTypeDescription
rowsintPattern height — also the fixed width of the inner loop.
iintOuter loop — current row; controls how many leading spaces print.
jintInner loop — prints space when j > i, else prints j.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from rows down to 1:
        if j > i: print space
        else: print j
    print newline

Approach comparison

ApproachIdeaBest for
if/else1, 21, …Learning and interviews
Ternary operator(j > i) ? printf(" ") : printf("%d", j)Compact console programs
User-input rowsscanf("%d", &rows);Flexible row count

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Inner loopfor (j = rows; j >= 1; j--)
Leading spacesif (j > i) printf(" "); else printf("%d", j);
End the rowprintf("\n");
Ternary form(j > i) ? printf(" ") : printf("%d", j);
User inputscanf("%d", &rows);

📋 if/else vs Ternary vs User Input

Same right-aligned triangle — different ways to write the condition and control rows.

Outer loop
i = 1..rows

One right-aligned row per iteration

Leading spaces
j > i ? " " : j

Space or digit

Inner loop
j = rows..1

Fixed width each row

Learning tip
rows - i

Leading spaces per row

Context

When This Pattern Shows Up

Reach for this pattern when teaching fixed-width loops, leading-space padding, and conditional character output.

  1. Post alignment exercise

    Natural follow-up after Program 29 — introduces right alignment with a single inner loop.

  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 29 (spaced mirror) and Program 31 (number-star diamond) 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 row count between 3 and 9 and draw the right-aligned descending triangle 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 rows, user input with ternary form, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the right-aligned descending triangle with if/else in one inner loop.

Example 1 — Fixed rows = 5

Hard-coded row count — 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 (j > i)
                printf(" ");
            else
                printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}

How It Works

When i = 1, the inner loop prints four spaces then 1 — output 1. When i = 5, no leading spaces — output 54321.

📈 User Input

Read the row count with scanf instead of hard-coding 5.

Example 2 — User Input

Read rows with scanf("%d", &rows); the inner loop uses rows as the fixed width.

c
#include <stdio.h>

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

    printf("Enter rows: ");
    scanf("%d", &rows);
    if (rows < 1) return 0;

    for (i = 1; i <= rows; ++i) {
        for (j = rows; j >= 1; --j)
            (j > i) ? printf(" ") : printf("%d", j);

        printf("\n");
    }

    return 0;
}

How It Works

Same right-aligned core as Example 1; a ternary operator replaces if/else and rows replaces hard-coded 5. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Smaller Demo

Run with rows = 3 to trace every row on paper before scaling up.

Example 3 — Compact rows = 3

Same if/else logic with a smaller row count for quick tracing.

c
#include <stdio.h>

int main() {
    int rows = 3;
    int i, j;

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

    return 0;
}

How It Works

Only rows changes from 5 to 3 — the if/else structure stays identical. Trace i = 1, 2, 3 on paper to see how leading spaces shrink each row.

🧠 How the Algorithm Prints Rows

1

Set up

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

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — ascending outer loop; one right-aligned row per iteration.

Row
3

Inner loop (j)

for (j = rows; j >= 1; j--) — print space if j > i, else print j.

Padding
4

New line

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

Break
=

Right-aligned triangle complete

Leading spaces shrink each row — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, leading-space count, digit range, and full row output.

iLeading spacesDigits printedRow output
1411
232, 121
323, 2, 1321
414, 3, 2, 14321
505, 4, 3, 2, 154321

Leading spaces per row = rows - i — zero when i = rows.

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: flip j > i to j <= i for spaces and watch alignment break.

2. Pattern Series Base

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

Example: continue to Program 31 for a number-star diamond pattern.

3. Console Formatting Drills

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

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

4. Padding character

Add spaces between digits once the two-loop structure works.

Example: use printf("%d ", j) between digits for wider spacing.

5. Complexity Intuition

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

Example: count printed characters for rows = 5 — each row prints exactly rows characters.

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 rows = 3 before coding — watch how leading spaces shrink each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Keep Fixed Width

    Inner loop must always run rows times — spaces pad the left side.

  2. 2. Prefer scanf

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

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

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

  4. 4. Trace j > i on Paper

    Mark which positions print spaces vs digits for each row before coding.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

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 right-aligned descending triangles.

  1. 1. Newline Inside the Inner Loop

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

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

  2. 2. Flipping the Condition

    Using j <= i for spaces (instead of j > i) inverts which positions print digits.

    → Print space when j > i; print digit otherwise.

  3. 3. Wrong Inner Direction

    for (j = 1; j <= rows; j++) prints ascending digits — not the descending order this pattern needs.

    → Keep for (j = rows; j >= 1; j--) so digits read i..1.

  4. 4. Short Inner Loop

    Running the inner loop only to i removes leading spaces — output becomes left-aligned.

    → Inner loop must always run from rows down to 1.

  5. 5. Unchecked scanf

    Letters or empty input leave rows uninitialized.

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

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit row

Output is 1 (with rows - 1 leading spaces).

rows = 0

Empty pattern

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

Negative

rows < 0

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

rows = 2

Smallest triangle

Two rows: 1 and 21.

Bad input

Non-numeric scanf input

Unchecked scanf leaves rows unset — check the return value.

Large rows

Large row count

Each row prints exactly rows characters — total work grows as .

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Spaced mirror

2. Reverse descending

  • Compare with Program 3
  • Same digits, no leading spaces

3. Number-star diamond

  • Continue with Program 31
  • Alternating digits and stars

4. Safe input loop

  • Check scanf return value until rows >= 1
  • Then draw the triangle

Notes

  • Padding rule. Print space when j > i; print digit j otherwise. Inner loop always runs rows times.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 prints one digit with rows - 1 leading spaces.
  • Leading spaces per row = rows - i — compare with Program 3 where there are no leading spaces.

Quick Takeaway: outer loop i = 1..rows, inner j > i ? " " : j, then printf("\n").

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The right-aligned descending number triangle is a compact lesson in fixed-width loops and leading-space padding: print spaces while j > i, then print digits in descending order, and end each row with printf("\n"). Master the fixed-rows version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 31 for the number-star diamond pattern.

Inner loop must always use rows as the width — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Inner: if (j > i) print space, else print j
  • Keep inner loop at fixed width rows
  • Check scanf return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside the inner loop
  • Shorten the inner loop below rows
  • Flip the space/digit condition (j <= i for spaces)
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this right-aligned triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Fixed width

j = rows..1

Code
03

Leading spaces

rows - i per row

Code
04

Digits

Print i..1

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Leading spaces are printed while j > i. Smaller rows get more spaces, pushing digits to the right edge.
The inner loop runs j from rows down to 1. When j <= i, it prints j — naturally producing i..1 on each row.
Running j from rows down to 1 on every row keeps column alignment. Spaces fill positions where j > i.
Program 3 prints a left-aligned reverse descending triangle with no leading spaces. Program 30 pads with spaces for right alignment.
Replace 5 with rows in the inner loop bound — see Example 2.
O(n²) for n rows because each row runs a fixed-width inner loop of n iterations.
Check scanf's return value: if (scanf("%d", &rows) != 1) handle bad input. Unchecked scanf leaves rows uninitialized on failure.
One row prints with no leading spaces — just 1.
Yes — (j > i) ? printf(" ") : printf("%d", j) compacts the if/else logic.

Did you Know? 🔊

This pattern uses a fixed column width (rows). For each row i, the inner loop prints spaces while j > i, then prints digits in descending order — producing a right-aligned triangle.

Continue to Program 31

Move on to the number-star diamond pattern in the C number-pattern series.

Program 31 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