Square Number Pyramid in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Math

What You’ll Learn

The square number pyramid prints 1, then 4 9 16, then 25 36 49 64 81, … — a natural step after Program 40’s alternating 1/0 pattern. This tutorial covers odd-length rows, indentation centering, a running counter m, fixed-width formatting, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

m² per value

Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.

Outer Loop

i = 1, 3, 5…

for (i = 1; i <= 9; i += 2) — odd values set how many squares print per row.

Indent Loop

Center rows

for (j = i; j < 9; j++) prints leading spaces so the pyramid stays centered.

Counter m

Running sequence

Print m*m, then m++ — squares progress 1, 4, 9, 16, 25, … continuously.

Live Preview

2–5 levels

Pick a level count and draw the square-number pyramid in the browser.

O(n²)

Complexity

Total square prints = for n levels; extra memory stays O(1).

Introduction

A square number pyramid prints perfect squares in centered rows of odd length — 1, then 3, then 5 squares per row. With five levels, the output starts with 1, then 4 9 16, then 25 36 49 64 81, and continues.

In C# the outer loop steps i by 2, an indent loop prints leading spaces, and an inner loop prints {0,4}-formatted m*m values while incrementing m.

Why it matters?

It combines nested loops with math and formatted output — a key step after Program 40’s alternating rows.

Key Highlights

Odd row widths

Each row prints i squares.

Centering

Indent loop shifts narrow rows right.

vs Program 40

Program 40 alternates 1/0; Program 41 prints perfect squares.

Series Foundation

Follow Program 40; continue to Program 42 next.

In short: outer i += 2, indent spaces, inner print {0,4} of m*m, then m++ and WriteLine().

📝 Problem & Approach

Given a level count (e.g. 5 odd-width rows), print a centered pyramid of perfect squares using a running counter m and fixed-width columns.

C#
// 5 levels (i = 1, 3, 5, 7, 9)
//        1
//    4   9  16
//25  36  49  64  81
//...

Inputs & Outputs

ItemTypeDescription
levelsintNumber of pyramid rows — outer loop uses odd i up to 2*levels - 1.
iintOuter loop — odd row width (1, 3, 5, …); also drives indent count.
mintRunning counter — each printed value is m*m, then m++.

Minimal workflow

Pseudocode
set m = 1
for i from 1 to maxWidth step 2:
    print (maxWidth - i) pairs of spaces
    repeat i times:
        print m*m with fixed width
        m++
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + counter1, 4 9 16, …Learning and interviews
User-input levelsmaxWidth = 2*levels - 1Flexible console programs
Left-alignedSkip indent loopEasier tracing on paper

⚡ Quick Reference

GoalPattern
Walk odd rowsfor (i = 1; i <= 9; i += 2)
Indent spacesfor (j = i; j < 9; j++) Console.Write(" ");
Print squaresConsole.Write("{0,4}", m * m); m++;
End the rowConsole.WriteLine();
User inputint.TryParse(Console.ReadLine(), out levels)
Program 40 contrastAlternating 1/0 with shrinking rows — no m*m

📋 Fixed Levels vs User Input vs Left-Aligned

Same square-number pyramid — different ways to control size and alignment.

Outer loop
i += 2

Odd row widths

Indent loop
j = i..max-1

Centers the pyramid

Counter
m*m

Perfect squares

Formatting
{0,4}

Fixed-width columns

Context

When This Pattern Shows Up

Reach for this pattern when teaching formatted output, running counters, and centered pyramids.

  1. Post Program 40 exercise

    Natural follow-up after Program 40 — same nested-loop skills but adds math and column alignment.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with ReadLine for a flexible row count.

  4. Gateway to variants

    Compare Program 40 (alternating 1/0) and Program 42 (next in series) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a level count between 2 and 5 and draw the square-number pyramid in the browser.

Try 2, 3, or 4. Max up to 5 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C# programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five levels of the square-number pyramid with nested loops and formatted output.

Example 1 — Fixed 5 Levels

Hard-coded pyramid — ideal for first demos and screenshots.

C#
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

When i = 1, one square prints — 1. When i = 3, three squares print — 4 9 16 (from m = 2, 3, 4). The indent loop shifts narrow rows right so the pyramid stays centered.

📈 User Input

Read the level count from the console instead of hard-coding five rows.

Example 2 — User Input Levels

Read levels from the console with safe parsing.

C#
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 < 1) 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();
            }
        }
    }
}

How It Works

Same inner-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Left-Aligned

Skip the indent loop to print squares flush left — easier to trace on paper.

Example 3 — Left-Aligned Pyramid

Same squares and counter — no leading spaces.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int m = 1;

            for (int i = 1; i <= 9; i += 2)
            {
                for (int k = 1; k <= i; k++)
                {
                    Console.Write("{0,4}", m * m);
                    m++;
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

Only the indent loop is removed — m*m and {0,4} formatting stay the same as Example 1. Rows grow wider to the right without centering.

🧠 How the Algorithm Prints Rows

1

Set up

using System; brings in Console. Set m = 1 and loop variables i, j, k for 5 levels.

Setup
2

Outer loop walks rows

for (i = 1; i <= 9; i += 2) — odd values 1, 3, 5, 7, 9 set how many squares print per row.

Row
3

Indent loop (j)

for (j = i; j < 9; j++) — prints leading spaces so narrow rows stay centered.

Center
4

Print squares (k)

Console.Write("{0,4}", m * m); m++; — fixed-width perfect squares in sequence.

Squares
5

New line

Console.WriteLine() ends the row after the print loop finishes.

Break
=

Square-number pyramid complete

Total prints for 5 levels = 1+3+5+7+9 = 25O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — 5 Levels

Trace each outer-loop value of i, indent count, square count, m range, and row output.

iSpacesSquaresm rangeValues
18 pairs111
36 pairs32–44 9 16
54 pairs55–925 36 49 64 81
72 pairs710–16100 121 144 … 256
90 pairs917–25289 324 … 625

Squares per row = i — total prints = 1+3+5+7+9 = 25 = 5² for 5 levels.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change {0,4} to {0,5} when squares exceed 999.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 42 for the next pattern in the series.

3. Console Formatting Drills

Practice Write vs WriteLine without complex math.

Example: put WriteLine inside the inner loop by mistake.

4. Spaced Output

Add spaces or wider field width once the three-loop structure works.

Example: use Console.Write("{0,5}", m * m) for larger pyramids.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed squares for 5 levels — total is 25 ().

6. Input Validation Labs

Pair the pattern with TryParse and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C# courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Change to cubes, widen columns, or add more levels with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i, m, and indent count on paper for 3 levels before coding — watch how row width grows by 2 each time.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Match Loop Bounds

    Outer loop steps by 2 (i += 2); indent bound must equal the maximum i.

  2. 2. Prefer TryParse

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep WriteLine Outside

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Use Fixed-Width Format

    Console.Write("{0,4}", m * m) keeps columns aligned as values grow from 1 to 625.

  5. 5. Dry-Run 3 Levels

    Trace i = 1, 3, 5 on paper before coding the full 5-level demo.

Pro Tip: if the output is a vertical list of single squares per line, you almost certainly put WriteLine inside the print loop.

Common Pitfalls

Mistakes that commonly break square-number pyramids.

  1. 1. WriteLine Inside the Inner Loop

    Each square lands on its own line — you get a column, not a pyramid.

    → Use Write("{0,4}", m*m) for squares; WriteLine only after the print loop.

  2. 2. Forgetting to Increment m

    Printing m*m without m++ repeats the same square on every column.

    → Call m++ after each printed square inside the inner loop.

  3. 3. Mismatched Indent Bound

    Indent loop bound must match the outer maximum (9 for 5 levels, or maxWidth in Example 2).

    → Use for (j = i; j < maxWidth; j++) with maxWidth = 2*levels - 1.

  4. 4. Field Width Too Small

    {0,4} breaks alignment when squares reach 1000+ — columns overlap.

    → Increase to {0,5} or {0,6} for larger pyramids.

  5. 5. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single square row

One level prints just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Two levels

Two rows: centered 1 and 4 9 16.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Each row prints i squares — total work grows as for n levels.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Alternating pattern

  • Review Program 40’s 1/0 rows
  • Compare with Program 40

2. Print cubes

  • Change m*m to m*m*m
  • Widen the format field for larger values

3. Next in series

  • Continue with Program 42
  • Build on nested loops + math

4. Left-aligned

  • Remove the indent loop
  • Same counter, no centering

Notes

  • Loop rule. Outer: i = 1, 3, 5…. Indent: j = i..max-1. Print: k = 1..i with m*m.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Row i prints exactly i squares — total for n levels = (sum of first n odd numbers).

Quick Takeaway: outer i += 2, indent spaces, print {0,4} of m*m with m++, then WriteLine().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The square number pyramid is a compact nested-loop lesson: odd-width rows, indentation centering, a running counter m, and fixed-width m*m output. Master the fixed-level version, then try user input and the left-aligned variant.

Practice the three examples above, then continue to Program 42 for the next pattern in the series.

Row i prints i squares from m*m — keep WriteLine outside the print loop and match indent bound to maxWidth.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= maxWidth; i += 2) in the outer loop
  • Indent: for (j = i; j < maxWidth; j++) prints leading spaces
  • Print {0,4} of m*m and increment m each time
  • Validate levels ≥ 1 for interactive programs
  • Prefer int.TryParse over bare Convert.ToInt32

❌ Don’t

  • Call WriteLine inside the square-print loop
  • Forget m++ after each printed square
  • Use a mismatched indent bound for the pyramid width
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this square-number pyramid

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

i += 2 (odd widths)

Code
03

Counter

m*m then m++

Code
04

Format

{0,4} alignment

Output
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A centered pyramid of perfect squares: row 1 prints 1 (1²), row 2 prints 4 9 16 (2², 3², 4²), and so on.
The outer loop increases i by 2 each time (i += 2), so i takes odd values — each becomes the count of squares printed on that row.
An indentation loop prints spaces before each row. As i grows, fewer spaces are printed, so wider rows shift left and stay centered.
m starts at 1 and increments after every printed square. Each value printed is m*m — the next perfect square in sequence.
Fixed-width columns keep the pyramid aligned as squares grow from 1 to 625. Without it, columns drift apart.
Increase the outer-loop maximum (e.g. i <= 11) and match the indent bound — or use levels input as in Example 2.
Program 40 alternates 1 and 0 with shrinking rows. Program 41 prints perfect squares in a centered pyramid with growing odd-width rows.
O(n²) for n levels — total prints are 1+3+5+...+(2n-1) = n².
For many levels, m*m overflows int. Switch m to long when squares exceed about 46340.

Did you Know? 🔊

Each printed value is from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total prints for n levels = .

Continue to Program 42

Move on to the next pattern in the C# number-pattern series.

Program 42 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful