Centered Palindrome Number Pyramid in C

What You’ll Learn
How to print a centered pyramid where each row forms a palindrome: numbers increase from 1 up to the row number, then decrease back to 1.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1Complete C Program
We print leading spaces, then numbers ascending 1..i, then descending i-1..1.
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int space = 1; space <= rows - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
for (int k = i - 1; k >= 1; k--) {
printf("%d ", k);
}
printf("\n");
}
return 0;
}🧠 How It Works
Print leading spaces
rows - i space groups keep the pyramid centered.
Ascending part
Print numbers from 1 to i.
Descending part
Print numbers from i-1 down to 1 to mirror the row.
Centered palindrome pyramid
Every row reads the same forward and backward.
Variation — User Input Version
Read the number of rows using scanf().
#include <stdio.h>
int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (int i = 1; i <= rows; i++) {
for (int space = 1; space <= rows - i; space++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
for (int k = i - 1; k >= 1; k--) {
printf("%d ", k);
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Change spacing (one space vs two spaces) for a tighter pyramid
- Remove the spacing loop to left-align the pyramid
- Replace numbers with letters to create an alphabet pyramid
Avoid
- Using
rows <= 0without validating input - Forgetting the descending loop (breaks the palindrome)
Key Takeaways
Leading spaces center each row.
Rows print ascending then descending numbers to form a palindrome.
Row i prints 2i-1 numbers.
Total runtime is O(n²).
❓ Frequently Asked Questions
i is already printed as the peak. Printing i-1..1 mirrors the left side without duplicating the center.printf(" ") to printf(" ") for tighter centering.n rows.Explore More C Number Patterns!
Try more pyramid and palindrome patterns to strengthen your nested-loop skills.
The widest row prints 2*rows - 1 numbers. For rows=5, that’s 9 values.
12 people found this page helpful
