C++ Number Pyramid Pattern (Centered Continuous)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A centered continuous number pyramid grows with odd row widths (1, 3, 5…), leading spaces for centering, and a running counter that never resets.

Remember
Rule: k = 1 before loops
      for i from 1 to max step 2
        for j from max down to 1
          if j > i: print space
          else: print k, then k++

    1
  2 3 4
5 6 7 8 9     ← max = 5 (spaces shown)

Follows the number & asterisk mirror in Program 23; next is the bidirectional number triangle in Program 25.

How to Solve It

Outer loop walks odd widths with i += 2. Reverse inner loop prints a space when j > i, else k++.

MethodIdeaBest for
Spaces + k++Reverse scan: space if j > i, else print and bump kLearning, interviews, exams
Separate space loopPrint (max - i) / 2 spaces, then i numbersClearer centering when you prefer two loops

Pseudocode

Pseudocode
k = 1
for i from 1 to max step 2:
    for j from max down to 1:
        if j > i:
            print space
        else:
            print k and a space
            k = k + 1
    print newline

Cheat sheet

GoalPattern
Odd row widthsfor (i = 1; i <= max; i += 2)
Init counter onceint k = 1; before the outer loop
Reverse columnsfor (j = max; j >= 1; j--)
Space vs numberif (j > i) cout << " "; else cout << k++ << " ";
Force odd maxif (max % 2 == 0) max -= 1;

Printing Numbers vs Starting a New Line

APIEffectUse for
cout << " " / k++ << " "Stays on the same lineSpaces and numbers on the row
cout << "\n"Ends the current lineAfter the inner loop finishes

Print characters without a newline, then end the row once.

Live Preview

Change the max odd width and the pyramid updates instantly — even values snap down to odd; capped at 9 for readable demos.

Whole numbers from 1 to 9. Even values are adjusted down by 1. Tap a chip or type — the preview redraws as you go.

Live result max = 5 · 9 numbers
    1 
  2 3 4 
5 6 7 8 9 

Worked Walkthrough — max = 5

Trace how odd i, leading spaces, and persistent k build each row.

iSpacesNumbersk afterPrints
14121
322 3 452 3 4
505 6 7 8 9105 6 7 8 9

Spaces when j > i = max - i. Total numbers = sum of odd widths → O(n²) for max width n.

C++ Programs

Three complete programs: fixed max = 5, cin input, and a compact max = 3 demo. Use View Output to reveal sample results.

Example 1 — Fixed max = 5

Hard-coded width — odd outer loop, reverse inner loop with space vs k++.

C++
#include <iostream>
using namespace std;

int main()
{
    int max = 5;
    int i, j;
    int k = 1;

    for (i = 1; i <= max; i += 2)
    {
        for (j = max; j >= 1; j--)
        {
            if (j > i)
                cout << " ";
            else
                cout << k++ << " ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Odd widths. i becomes 1, 3, 5 — each value is how many numbers that row prints.

2. Space or number. When j > i print a space; otherwise print k++.

3. Keep k alive. k sits outside the outer loop so numbers continue across rows.

Example 2 — User Input Max

Read max with cin, validate, and force odd so every row width stays odd.

C++
#include <iostream>
using namespace std;

int main()
{
    int max;
    int i, j;
    int k = 1;

    cout << "Enter the maximum odd width: ";
    if (!(cin >> max) || max <= 0)
    {
        cout << "Please enter a positive integer.\n";
        return 1;
    }

    if (max % 2 == 0)
        max -= 1;

    for (i = 1; i <= max; i += 2)
    {
        for (j = max; j >= 1; j--)
        {
            if (j > i)
                cout << " ";
            else
                cout << k++ << " ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Prompt and validate. Reject failed reads and non-positive values before printing.

2. Force odd. if (max % 2 == 0) max -= 1; keeps row widths odd.

3. Safer input tip. Cap demos for readable output:

Safer input
if (!(cin >> max) || max < 1 || max > 9)
{
    cout << "Enter a whole number from 1 to 9.\n";
    return 1;
}

Example 3 — Compact max = 3

Same structure with only two rows — easy to confirm spaces and the running counter.

C++
#include <iostream>
using namespace std;

int main()
{
    int max = 3;
    int i, j;
    int k = 1;

    for (i = 1; i <= max; i += 2)
    {
        for (j = max; j >= 1; j--)
        {
            if (j > i)
                cout << " ";
            else
                cout << k++ << " ";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Two rows. i = 1 → two spaces then 1; i = 3 → 2 3 4.

2. Trace on paper. If you reset k = 1 inside the outer loop, every row restarts — that is not this pattern.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for max = 5 or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

reset k

Counter restarts each row

Declaring k = 1 inside the outer loop restarts the sequence. Keep k outside both loops.

no spaces

Left-aligned pyramid

Skipping if (j > i) leaves numbers flush left. Print a space when j > i.

i++

Wrong step

Using i++ prints every width. For odd lengths only, keep i += 2.

even max

Even maximum

If max is even, subtract 1 so the last row stays odd-width — see Example 2.

\n inside

Broken rows

If cout << "\n" sits inside the inner loop, each column lands on its own line. Call it only after the row finishes.

cin

Check the stream

Validate cin >> max before looping — a failed read leaves max unset or stale.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Compact max = 3 (Example 3)O(n²)O(1)

About n/2 rows each scan n columns → O(n²) time. Only a few loop variables are needed.

Key Takeaways

  • Odd widths: i += 2 gives row lengths 1, 3, 5…
  • Center with spaces: print a space when j > i, else print k++.
  • Keep k alive: init once before the outer loop so numbers continue across rows.
  • Complexity: O(n²) time from scanning n columns per odd row; O(1) extra space.

One line: for each odd i, scan columns reverse — space if j > i, else k++, then newline.

Frequently Asked Questions

A centered continuous pyramid: for max=5 you get a centered 1, then 2 3 4, then 5 6 7 8 9 — odd row widths with a running counter that never resets.
The program prints a space when j > i, which shifts the numbers right and centers each row within max columns.
Because the counter k is declared once before the outer loop and increments with k++ every print — it never resets per row.
Row widths are odd (1, 3, 5, …) so each row adds two more numbers than the previous row.
cout << " " stays on the same line for spaces and numbers. cout << "\n" ends the current row after the inner loop finishes.
The reverse inner loop prints leading spaces first (when j > i) and numbers afterward — a common centering trick.
Subtract 1 to force an odd width so every row length stays odd.
O(n²) for max width n because each of about n/2 rows iterates across n columns.

Did you know?

This centered pyramid prints numbers continuously using a counter k. An if inside a reverse loop prints leading spaces when j > i, then prints k++ once the column reaches the row boundary.

Next: Bidirectional Number Triangle

Continue with a triangle that prints ascending and descending digits on each row.

Program 25 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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