Square Number Pyramid in C

What You’ll Learn
How to print a centered square number pyramid in C using a running counter m. Each printed value is m*m, producing squares like 1, 4, 9, 16, and so on.
⭐ Pattern Output
For a maximum row width of 9 (odd), the pattern looks like this:
1
4 9 16
25 36 49 64 81
100 121 144 169 196 225 256
289 324 361 400 441 484 529 576 625Complete C Program
Print odd counts per row (1, 3, 5, 7, 9). Use spaces to center-align and %4d to align squares.
#include <stdio.h>
int main() {
int i, j, k;
int m = 1;
for (i = 1; i <= 9; i += 2) {
for (j = i; j < 9; ++j) {
printf(" ");
}
for (k = 1; k <= i; ++k) {
printf("%4d", m * m);
++m;
}
printf("\n");
}
return 0;
}🧠 How It Works
Use a running counter
m starts at 1 and increases after each print. We output m*m to get squares.
Print odd-length rows
i takes values 1, 3, 5, 7, 9 using i += 2.
Center with leading spaces
The first inner loop prints spaces so the pyramid stays centered as rows get wider.
Format with %4d
%4d reserves 4 characters per value, keeping columns aligned.
Square pyramid
Total prints for 5 rows are 1+3+5+7+9 = 25, so time complexity is O(n²).
Variation — User Input Version
Accept an odd maximum width from the user (like 9, 11, 13) and print the pyramid up to that size:
#include <stdio.h>
int main() {
int i, j, k;
int m = 1;
int maxRow;
printf("Enter the maximum row number (odd): ");
scanf("%d", &maxRow);
for (i = 1; i <= maxRow; i += 2) {
for (j = i; j < maxRow; ++j) {
printf(" ");
}
for (k = 1; k <= i; ++k) {
printf("%4d", m * m);
++m;
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Print cubes by changing
m*mtom*m*m - Tune spacing by adjusting
%4dand the leading-space loop - Start the sequence from a different number by changing
m - Make it left-aligned by removing the leading spaces loop
Avoid
- Using an even
maxRowif you want perfectly symmetric odd-length rows - Removing
%4dformatting while still expecting alignment - Resetting
minside the loops (it must be continuous)
Key Takeaways
Each printed value is a perfect square: m*m.
Row widths are odd numbers: 1, 3, 5, 7, 9.
%4d keeps multi-digit squares aligned.
Total prints follow n² for n rows.
❓ Frequently Asked Questions
i += 2), which generates odd row lengths and keeps the pyramid symmetric.%4d reserves enough space so the columns stay aligned.m * m with m * m * m.1+3+...+(2n-1) = n².Explore More C Number Patterns!
Keep practicing with more pyramids, triangles, and number sequences.
The sum of the first n odd numbers is n². That’s why 1+3+5+7+9 = 25 prints for 5 rows.
6 people found this page helpful
