Java Number Pyramid Pattern (Centered Continuous)

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

What Is This Pattern?

A centered continuous number pyramid prints odd-width rows with leading spaces, while a single counter k keeps rising across every row.

Remember
Rule: for odd i up to max,
      reverse-scan columns — space when j > i, else print k++

    1
  2 3 4
5 6 7 8 9     ← max = 5

Unlike Program 20 (left-aligned continuous triangle), this version centers each row with a reverse inner loop and an if (j > i) space check.

How to Solve It

Odd outer widths, reverse inner scan, shared counter k.

MethodIdeaBest for
Reverse + ifScan j from max down; space when j > i, else k++Learning, interviews, exams
Safe ScannerSame loops; re-prompt until hasNextInt() succeedsConsole apps that must reject bad input

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

Cheat sheet

GoalPattern
Odd row widthsfor (int i = 1; i <= max; i += 2)
Start counter onceint k = 1; before the outer loop
Reverse columnsfor (int j = max; j >= 1; j--)
Space vs numberif (j > i) print(" "); else print(k++ + " ");
End the rowSystem.out.println();
Even max fixif (max % 2 == 0) max -= 1;

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineLeading spaces and each k++
System.out.printlnEnds the current lineAfter the inner loop

Print spaces and numbers without a newline, then end the row once.

Live Preview

Change the max odd width and the centered pyramid updates instantly. Even values are adjusted down by 1.

Whole numbers from 1 to 9. Tap a chip or type a value — the preview redraws as you go.

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

Worked Walkthrough — max = 5

Trace spaces, printed numbers, and k after each row.

iLeading spacesNumbersk afterPrinted row
14 (j = 5..2)121
32 (j = 5..4)2 3 452 3 4
505 6 7 8 9105 6 7 8 9

Each row scans all max columns — total work is O(n²) for width n.

Java Programs

Three complete programs: fixed max = 5, Scanner input with even-width fix, and a safe re-prompt loop. Use View Output to reveal sample results.

Example 1 — Fixed max = 5

Hard-coded width — reverse inner loop centers each row; k never resets.

Java
public class CenteredPyramid {
    public static void main(String[] args) {
        int k = 1;

        for (int i = 1; i <= 5; i += 2) {
            for (int j = 5; j >= 1; j--) {
                if (j > i)
                    System.out.print(" ");
                else
                    System.out.print(k++ + " ");
            }
            System.out.println();
        }
    }
}

How It Works

1. Odd widths. i takes values 1, 3, 5 — that many numbers print on each row.

2. Reverse scan. j runs from max down to 1. While j > i, print a leading space.

3. Continuous counter. Otherwise print k++. k sits outside the outer loop, so values continue across rows.

When i = 1, four spaces then 1. When i = 3, two spaces then 2 3 4.

Example 2 — Max Input

Read max at runtime. Adjust even widths down so row sizes stay odd.

Java
import java.util.Scanner;

public class CenteredPyramidInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the maximum odd width: ");
        int max = sc.nextInt();

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

        int k = 1;
        for (int i = 1; i <= max; i += 2) {
            for (int j = max; j >= 1; j--) {
                if (j > i)
                    System.out.print(" ");
                else
                    System.out.print(k++ + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Prompt and read. Ask for a max width, then store it with sc.nextInt().

2. Keep it odd. if (max % 2 == 0) max -= 1; so entering 6 becomes 5.

3. Same pyramid core. Spacing and k++ match Example 1 — only the source of max changes.

Example 3 — Safe Input with Scanner Loop

Re-prompt until a positive whole number is entered, then draw the pyramid.

Java
import java.util.Scanner;

public class CenteredPyramidSafe {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int max = 0;

        System.out.print("Enter the maximum odd width: ");
        while (max < 1) {
            if (sc.hasNextInt()) {
                max = sc.nextInt();
                if (max < 1)
                    System.out.print("Please enter a positive whole number: ");
            } else {
                sc.next();
                System.out.print("Please enter a positive whole number: ");
            }
        }

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

        int k = 1;
        for (int i = 1; i <= max; i += 2) {
            for (int j = max; j >= 1; j--) {
                if (j > i)
                    System.out.print(" ");
                else
                    System.out.print(k++ + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Validate in a loop. Stay in while (max < 1) until a positive int arrives.

2. Clear bad tokens. On non-numeric input, sc.next() discards the token and re-prompts.

3. Then draw. After validation (and the even-width fix), the same reverse-loop pyramid runs.

Edge Cases & Pitfalls

Check these before calling the solution done.

k inside

Reset each row

Declaring k inside the outer loop restarts at 1 every row. Keep k before the loops.

i++

Even widths

Using i++ prints every length. Use i += 2 for the odd pyramid shape.

Forward j

Spaces on the right

Scanning j upward puts spaces after numbers. The reverse scan (j from max down) puts spaces on the left.

println inside

Broken rows

If println is inside the inner loop, each column lands on its own line. Use print for spaces and numbers; println only after the inner loop.

max = 1

Single 1

Output is just 1 — a good sanity check.

Even max

Adjust down

Without the even fix, odd i still stops at the last odd width — subtract 1 explicitly for clarity.

Time and Space Complexity

ProgramTimeExtra space
Centered pyramid (Examples 1–3)O(n²)O(1)

About (n + 1) / 2 rows, each scanning n columns — total work is quadratic in max width n.

Key Takeaways

  • Rule: odd i, reverse j — space when j > i, else print k++.
  • No reset: keep k outside the outer loop so numbers continue across rows.
  • Break the row: call println only after the inner loop.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each odd width, print leading spaces then k++, and never reset k.

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.
System.out.print stays on the same line for spaces and numbers. System.out.println 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 (see Example 2). This pattern assumes odd row sizes.
O(n²) for max width n because each row iterates across n columns.
Use sc.hasNextInt() before sc.nextInt(), require max ≥ 1, and re-prompt on failure — see Example 3.

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

Move on to the bidirectional number triangle in the Java 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