C Program to print Pattern 4 1 121 12321 1234321 123454321
Objective
Write a C program to print a pyramid of palindrome numbers.
Algorithm / Approach
- Run an outer loop
ifrom 1 to 5. - Run a first inner loop to print spaces (decreasing).
- Run a second inner loop
jfrom 1 up toi, printingj(ascending numbers). - Run a third inner loop starting from
i - 1down to 1, printingj(descending numbers). - Print a newline.
main.c
#include<stdio.h>
int main( ) {
int i,j;
for(i=1;i<=5;i++) {
for(j=4;j>=i;j--) {
printf(" ",j);
}
for(j=1;j<=i;j++) {
printf("%d",j);
}
for(j--;j>=1;j--) {
printf("%d",j);
}
printf("\n");
}
return 0;
}
Expected Output
1 121 12321 1234321 123454321
Explanation of the Program
- This pattern creates a pyramid where each row is a numerical palindrome (e.g., 12321).
- It is constructed using three distinct inner loops per row: one for the left padding spaces, one to count up to the peak number, and one to count back down to 1.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)