Right-Aligned Ascending Triangle in C

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Spacing + Nested Loops

What You’ll Learn

How to print a right-aligned triangle where each row contains 1 to i. The first loop prints spaces; the second loop prints the numbers.

⭐ Pattern Output

For rows = 5, the pattern looks like this:

Output
    1
   1 2
  1 2 3
 1 2 3 4
1 2 3 4 5
1

Complete C Program

Print rows - i leading spaces, then print numbers 1..i.

c
#include <stdio.h>

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

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

    return 0;
}
2

Variation — User Input Version

Accept the row count at runtime:

c
#include <stdio.h>

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

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

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

    return 0;
}

🧠 How It Works

1

Outer loop picks the row

i goes from 1 to rows.

Rows
2

Print leading spaces

The first inner loop prints rows - i spaces to shift the row to the right.

Alignment
3

Print numbers 1..i

The second inner loop prints increasing numbers from 1 up to the current row length.

Numbers

Key Takeaways

1

Spaces control right-alignment: print rows - i spaces.

2

Numbers are always 1..i (ascending).

3

Time complexity is O(n²) for n rows.

4

Removing the space loop makes it left-aligned.

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.

6 people found this page helpful