Right-Aligned Ascending Triangle in C

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 51
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.
6 people found this page helpful
