C Program to print Pattern 6 1234321 12321 121 1
Objective
Write a C program to print an inverted numerical pyramid.
Algorithm / Approach
- Run an outer loop
ifrom 1 to 5. - Run an inner loop to print spaces (increasing with
i). - Run an inner loop
jfrom 1 to5 - i(ascending numbers). - Run a final inner loop to print descending numbers back to 1.
- Print a newline.
main.c
#include<stdio.h>
int main( ) {
int i,j;
for(i=1;i<=5;i++) {
for(j=1;j<=i;j++) {
printf(" ");
}
for(j=1;j<=5-i;j++) {
printf("%d",j);
}
for(j=j-2;j>=1;j--) {
printf("%d",j);
}
printf("\n");
}
return 0;
}
Expected Output
1234321 12321 121 1
Explanation of the Program
- This is the exact opposite of a standard pyramid. Instead of starting with 1 item and growing to 5, it starts with a wide base and shrinks.
- To achieve the shrinking effect, the bounds of the inner loops must decrease as the outer loop counter (
i) increases (e.g.,5 - i).
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)