Square Number Pyramid in C#

What You’ll Learn
How to print a centered pyramid of square numbers in C# using nested loops and formatted output.
We increment a counter m and print m*m with a fixed width so the pyramid stays aligned.
⭐ Pattern Output
For this example, 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-length rows (1, 3, 5, 7, 9). Each printed value is the square of the running counter.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int i, j, k;
int m = 1;
for (i = 1; i <= 9; i += 2)
{
for (j = i; j < 9; j++)
Console.Write(" ");
for (k = 1; k <= i; k++)
{
Console.Write("{0,4}", m * m);
m++;
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Use odd row sizes
i takes values 1, 3, 5, 7, 9, which become the count of squares printed on each row.
Indentation for centering
The loop for (j = i; j < 9; j++) prints spaces so smaller rows start farther right.
Print squares using m*m
Each iteration prints m*m and increments m.
Fixed-width formatting
{0,4} keeps columns aligned as the squares grow (e.g., 1, 16, 625).
Variation — User Input Levels
This version lets the user choose how many odd-length rows to print (levels).
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int levels;
int m = 1;
Console.Write("Enter number of levels: ");
if (!int.TryParse(Console.ReadLine(), out levels) || levels <= 0)
{
Console.WriteLine("Please enter a positive integer.");
return;
}
int maxWidth = 2 * levels - 1;
for (int i = 1; i <= maxWidth; i += 2)
{
for (int j = i; j < maxWidth; j++)
Console.Write(" ");
for (int k = 1; k <= i; k++)
{
Console.Write("{0,4}", m * m);
m++;
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Use
longif you plan to print many squares (values grow quickly) - Change
m*mtom*m*mto print cubes instead of squares - Increase the indentation spacing if you add spaces between numbers
Avoid
- Using too small a field width (alignment will break for 3+ digit squares)
- Letting the counter overflow for large levels without switching types
Key Takeaways
Row lengths are odd: 1, 3, 5, 7, 9.
A counter generates the sequence; printing m*m gives squares.
Indentation centers the pyramid.
Formatted printing keeps columns aligned.
Explore More C# Number Patterns!
Square-number patterns combine loops with simple math—great practice for both.
The squares grow quickly: \(25^2 = 625\) already needs 3 digits. Fixed-width formatting keeps the pyramid aligned even as values increase.
12 people found this page helpful
