Centered Continuous Number Pyramid in C

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Spacing + Counter

What You’ll Learn

The centered continuous number pyramid prints 1, then 2 3 4, then 5 6 7 8 9 — a natural step after the mirror pattern in Program 23. This tutorial covers odd row widths, leading spaces, a running counter k, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

Centered pyramid

Row 1 prints 1, row 2 prints 2 3 4, row 3 prints 5 6 7 8 9 with leading spaces.

Outer Loop

i += 2

for (i = 1; i <= max; i += 2) sets odd row widths 1, 3, 5.

Spacing + Numbers

if (j > i)

Reverse loop prints spaces first, then k++ for each number slot.

Running Counter

k never resets

k = 1 before the outer loop; k++ continues across rows.

Live Preview

Odd widths 1–9

Pick a max odd width and draw the centered pyramid instantly in the browser.

O(n²)

Complexity

Each row scans max columns; total work scales as .

Introduction

A centered continuous number pyramid prints numbers that keep counting across rows, with leading spaces to center each row. With max width 5, the output is 1, 2 3 4, 5 6 7 8 9 (spaces shown in the worked examples below).

In C you use an outer loop with odd widths, a reverse inner loop with an if for spaces vs k++, then printf("\n") ends each row.

Why it matters?

It combines spacing logic with a persistent counter — a step up from Program 23’s three inner loops.

Key Highlights

Odd widths

i = 1, 3, 5 controls how many numbers print per row.

Leading spaces

if (j > i) prints spaces before numbers.

Continuous k

k++ never resets — numbers flow across rows.

Series Foundation

Follow Program 23; continue to Program 25 (bidirectional triangle) next.

In short: for each odd i, scan j from max down to 1 — print a space when j > i, else print k++, then printf("\n").

📝 Problem & Approach

Given a positive odd max width (e.g. 5), print a centered pyramid where numbers increase continuously across rows using a counter k.

c
// max = 5 (conceptual shape — dots show spaces)
// ··1·
// ·2·3·4
// 5·6·7·8·9

Inputs & Outputs

ItemTypeDescription
maxintMaximum odd row width — inner loop scans j from max down to 1.
iintOuter loop — odd row widths 1, 3, 5 via i += 2.
jintReverse inner loop — spaces when j > i, else print number.
kintRunning counter — starts at 1, increments with k++ across all rows.

Minimal workflow

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; k = k + 1
    print newline

Approach comparison

ApproachIdeaBest for
Spacing + counter1, 2 3 4, 5 6 7 8 9Learning and interviews
User-input maxscanf("%d", &max);Flexible console programs
Safe inputscanf loop + even-width adjustmentRobust user-facing demos

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= max; i += 2)
Init counterk = 1; before the outer loop
Scan columnsfor (j = max; j >= 1; j--)
Space or numberif (j > i) printf(" "); else printf("%d ", k++);
End the rowprintf("\n");
User inputscanf("%d", &max);

📋 Fixed max vs User Input vs Safe Input

Same centered pyramid — different ways to control width and input validation.

Outer loop
i += 2

Odd row widths 1, 3, 5

Spacing
j > i

Leading spaces center each row

Counter
k++

Numbers continue across rows

Learning tip
if/else

One inner loop handles space vs number

Context

When This Pattern Shows Up

Reach for this pattern when teaching centering with spaces, persistent counters, and if/else inside nested loops.

  1. Post mirror exercise

    Natural follow-up after Program 23 — introduces spacing logic and a running counter.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with scanf for a flexible row count.

  4. Gateway to variants

    Compare Program 23 (mirror pattern) and Program 25 (bidirectional triangle) 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 an odd max width between 1 and 9 and draw the centered continuous pyramid in the browser.

Try 3, 5, or 7. Even values are adjusted to the nearest odd width. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C programs — fixed max width, user input, and safe input with validation. Click View Output to reveal sample console results.

📚 Getting Started

Print three rows of the centered pyramid with a running counter.

Example 1 — Fixed max = 5

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

c
#include <stdio.h>

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

    for (i = 1; i <= 5; i += 2) {
        for (j = 5; j >= 1; --j) {
            if (j > i)
                printf(" ");
            else
                printf("%d ", k++);
        }
        printf("\n");
    }

    return 0;
}

How It Works

When i = 1, print two spaces then 1 — output 1. When i = 3, print one space then 2 3 4. When i = 5, print 5 6 7 8 9 with no leading spaces. k never resets, so numbers continue across rows.

📈 User Input

Read the maximum odd width with scanf instead of hard-coding 5.

Example 2 — User Input

Read max with scanf("%d", &max); adjust even widths to the nearest odd value.

c
#include <stdio.h>

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

    printf("Enter the maximum odd width: ");
    scanf("%d", &max);

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

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

    return 0;
}

How It Works

Same spacing + counter core as Example 1; only the source of max changes. The even-width adjustment keeps row sizes odd for a proper pyramid shape. Non-numeric input leaves max unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Safe Input

Check scanf return value so bad input does not leave max uninitialized.

Example 3 — Safe Input with scanf Loop

Validate input before drawing the pyramid — prompt again on failure.

c
#include <stdio.h>

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

    printf("Enter the maximum odd width: ");
    while (scanf("%d", &max) != 1 || max < 1) {
        printf("Please enter a positive whole number: ");
    }

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

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

    return 0;
}

How It Works

scanf returns something other than 1 on bad input — the loop re-prompts until a valid positive integer is entered, then the pyramid draws as usual.

🧠 How the Algorithm Prints Rows

1

Set up

#include <stdio.h> brings in printf / scanf. Set k = 1 and loop variables i, j.

Setup
2

Outer loop + odd widths

for (i = 1; i <= max; i += 2) — row widths 1, 3, 5 grow the pyramid.

Row
3

Reverse inner loop (j)

for (j = max; j >= 1; j--) scans columns from right to left.

Columns
4

Space or number

if (j > i) prints a space; else printf("%d ", k++).

if/else
5

New line

printf("\n") ends the row after the inner loop.

Break
=

Centered pyramid complete

Numbers continue across rows — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — max = 5

Trace each outer-loop value of i, leading spaces, numbers printed, and k after each row.

iLeading spacesNumbers printedk after rowRow output
12 (when j = 5, 4)121
31 (when j = 5)2, 3, 452 3 4
505, 6, 7, 8, 9105 6 7 8 9

Leading spaces per row = (max - i) / 2 when max is odd — centers each row.

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: put printf("\n") inside the inner loop by mistake.

2. Pattern Series Base

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

Example: reset k each row and compare output.

3. Console Formatting Drills

Practice printf vs row newline without complex math.

Example: put printf("\n") inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: print k++ + " " with padded widths for 2-digit numbers.

5. Complexity Intuition

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

Example: count printed numbers for max = 9 → 1 + 3 + 5 + 7 + 9 = 25.

6. Input Validation Labs

Pair the pattern with scanf return checks and positive-row checks.

Example: reject max <= 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

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace the reverse inner loop on paper for max = 3 before coding — spacing bugs hide in the j > i condition.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Do not reset k inside the outer loop unless you want per-row numbering.

  2. 2. Prefer scanf

    Check the return value so bad input does not leave max uninitialized.

  3. 3. Keep printf("\n") Outside

    Only call printf("\n") after the inner loop finishes the row.

  4. 4. Trace i and j on Paper

    Write each i, space count, and numbers printed before coding.

  5. 5. Dry-Run One Small n

    Trace max = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put printf("\n") inside the inner loop.

Common Pitfalls

Mistakes that commonly break centered pyramid patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use printf(" ") or printf("%d ", k++); printf("\n") only after the inner loop.

  2. 2. Resetting k Each Row

    Putting k = 1 inside the outer loop restarts numbering — you lose the continuous effect.

    → Initialize k = 1 once before the outer loop unless you want per-row numbering.

  3. 3. Forgetting Leading Spaces

    Without if (j > i) the pyramid is left-aligned, not centered.

    → Print a space when j > i before printing numbers.

  4. 4. Using Even Row Widths

    Even max values break the centering math for this version.

    → Subtract 1 when max % 2 == 0, or validate and prompt again.

  5. 5. Unchecked scanf

    Letters or empty input leave max uninitialized.

    → Check scanf return value and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

max = 1

Single row

Output is just a centered 1 with leading spaces.

max = 0

Empty pattern

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

Negative

max < 0

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

Even max

Even width entered

Subtract 1 to force odd width, or re-prompt for an odd value.

Bad input

Non-numeric scanf input

Unchecked scanf leaves max unset — check the return value.

max = 3

Smallest pyramid

Two rows: centered 1 and 2 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Mirror pattern

2. Bidirectional triangle

3. Reset k per row

  • Move k = 1 inside the outer loop
  • Compare continuous vs per-row numbering

4. Alphabet pyramid

  • Replace numbers with letters using k++ on chars
  • Same spacing logic applies

Notes

  • Centering. Leading spaces when j > i shift numbers right — row width stays at max columns.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate max > 0 for interactive programs; max = 1 prints a single centered 1.
  • Double-digit numbers need wider spacing — consider fixed-width formatting for large pyramids.

Quick Takeaway: odd outer loop (i += 2), reverse inner loop with if (j > i), persistent k++, then printf("\n") after each row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(n²)O(1)
Safe input (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The centered continuous number pyramid is a compact lesson in spacing and counters: print leading spaces when j > i, then k++ for each number slot. Master the fixed-max version, then try user input and safe scanf validation.

Practice the three examples above, then continue to Program 25 for the bidirectional number triangle.

Never reset k inside the outer loop unless you want per-row numbering — validate max when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= max; i += 2) in the outer loop
  • Initialize k = 1 before the outer loop
  • Print spaces when j > i, else k++
  • Check scanf return value before using max
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside the inner loop
  • Reset k inside the outer loop (unless intentional)
  • Skip leading spaces — the pyramid will be left-aligned
  • Use even max without adjustment
  • Ignore bad console input in user-facing demos
  • Skip the max = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this pyramid pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer i+=2

Odd widths

Code
+ 03

if j>i

Centering

Code
04

Continuous k

Never reset

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The program prints leading spaces when j > i, which shifts the numbers to the right and centers the pyramid.
Because the counter k is not reset inside the outer loop. It increments with k++ each time a number is printed.
Row widths are odd (1, 3, 5, …) so each row adds two more numbers than the previous row.
printf(" ") stays on the same line for spaces and numbers. printf("\n") ends the current row after the inner loop finishes.
The reverse inner loop lets you print leading spaces first (when j > i) and numbers afterward — a common centering trick.
Subtract 1 to force an odd width, or validate and prompt again. This version assumes odd row sizes.
O(n²) for max width n because each row iterates across n columns.
Check scanf's return value: if (scanf("%d", &max) != 1) handle bad input. Use a loop to re-prompt (see Example 3).
Only one row prints — a single centered 1 with leading spaces.

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.

Continue to Program 25

Move on to the bidirectional number triangle in the C number-pattern series.

Program 25 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