Concentric Number Square Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + max(i,j)

What You’ll Learn

The concentric number square prints symmetric rows where each value comes from max(i, j). The left half walks j = k..1 and the right half mirrors j = 2..k. This tutorial covers the rule, nested loops, live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

max(i,j)

Print j when j > i; otherwise print i — equivalent to max(i, j).

Left Half Loop

j = k..1

for (j = k; j >= 1; j--) builds the decreasing left side of each row.

Right Half Loop

j = 2..k

for (j = 2; j <= k; j++) mirrors the left half without duplicating the center.

Outer Loop

i = k..1

for (i = k; i >= 1; i--) — each row gets closer to the center value.

Live Preview

k = 3–10

Pick a value for k and draw the concentric number square instantly in the browser.

O(k²)

Complexity

Prints k rows with about 2k-1 values each — O(k²) total prints; memory stays O(1).

Introduction

A concentric number square pattern prints symmetric rows of numbers that decrease toward the center. With k = 5, the last row becomes 5 4 3 2 1 2 3 4 5.

In Java you loop i = k..1, then for each row print max(i, j) over the left half (j = k..1) and right half (j = 2..k).

Why it matters?

It teaches a reusable grid rule — once you spot max(i,j), the nested loops become straightforward.

Key Highlights

max(i,j) Rule

Each cell prints the larger of the row index and column value.

Left Half

j = k..1 produces the decreasing left segment.

Right Mirror

j = 2..k mirrors without repeating the center.

Series Foundation

Follow Program 45 star cross; continue to Program 47 concentric diamond.

In short: loop i = k..1, print max(i,j) for left and right halves, then println() after each row.

📝 Problem & Approach

Given k = 5, print k symmetric rows where each value equals max(i, j) over mirrored column loops.

Java
// k = 5 (conceptual shape)
// 5 5 5 5 5 5 5 5 5
// 5 4 4 4 4 4 4 4 5
// 5 4 3 3 3 3 3 4 5
// 5 4 3 2 2 2 3 4 5
// 5 4 3 2 1 2 3 4 5

Inputs & Outputs

ItemTypeDescription
kintMaximum value and row count (typically ≥ 1).
Printed outputtextk rows, each with 2k-1 space-separated numbers.

Minimal workflow

Pseudocode
for i from k down to 1:
    for j from k down to 1:
        print max(i, j)
    for j from 2 to k:
        print max(i, j)
    print newline

Approach comparison

ApproachIdeaBest for
if-else max rulej>i ? j : i in both halvesLearning and interviews
User-input ksc.nextInt();Flexible console programs
Math.max compactMath.max(i,j) in both loopsCleaner production-style code

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = k; i >= 1; i--)
Left halffor (j = k; j >= 1; j--)
Right halffor (j = 2; j <= k; j++)
Value rulej > i ? j : i or Math.max(i, j)
End the rowSystem.out.println();
Program 45 contrastStar cross uses symbol conditions; this pattern uses max(i,j) over mirrored number loops

📋 Left Half vs Right Half vs Combined

Same row cell — how max(i,j) picks the printed number.

Left half
j = k..1

Decreasing column walk — prints larger edge values first

Right half
j = 2..k

Mirrors the left segment without duplicating the center

Value rule
max(i,j)

Print j when j>i; otherwise print i

Learning tip
trace i=3,j=2

Dry-run cell (3,2): max(3,2) → prints 3

Context

When This Pattern Shows Up

Reach for this pattern when teaching max(i,j) inside mirrored column loops.

  1. First lab exercise

    Classic follow-up after concentric squares and diamonds.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible row count.

  4. Gateway to variants

    Compare with Program 45 (star cross), then continue to Program 47 (concentric diamond).

  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(k²) thinking.

🔮 Live Preview

Choose a value for k and draw the concentric number square in the browser.

Try 3, 5, or 7 for k (up to 10).

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed k, Scanner input, and a Math.max compact variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with mirrored inner loops and the max(i,j) rule.

Example 1 — Fixed k = 5

Hard-coded size — left half j=k..1, right half j=2..k, max rule in each cell.

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

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

How It Works

When i = 3, j = 2 on the left half, j > i is false — so the cell prints 3. When i = 1 on the last row, the center column prints 1.

📈 Practical Variant

Let the user choose k at runtime.

Example 2 — User Input Version

Read k with Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class ConcentricNumberSquareInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter k (e.g., 5): ");
        int k = sc.nextInt();

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

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of k changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Replace the if-else with Math.max(i, j) for cleaner code.

Example 3 — Math.max Compact

Use Math.max(i, j) in both inner loops — same output, less branching.

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

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

How It Works

Math.max(i, j) expresses the same rule as j > i ? j : i — easier to read once you know the pattern math.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set k (fixed or from input).

Setup
2

Outer loop (rows)

for (i = k; i >= 1; i--) — each row gets closer to the center value.

Row
3

Left half loop

for (j = k; j >= 1; j--) prints the decreasing left segment of each row.

Left
4

Inner loop + if

Both halves print max(i,j) with a trailing space, then println() ends the row.

Cells
=

Concentric number square pattern complete

Total cell visits equal k×(2k-1)O(k²) time, O(1) extra memory.

🔎 Worked Walkthrough — row i = 3, left j = 2

Trace one left-half cell to see the max(i,j) rule in action.

CheckResultPrints
j > i (2>3)falseprint i = 3
Equivalentmax(3,2)3
Row contexti=3, k=5middle row of five

Cell output: 3 — full row has 2k-1 = 9 values when k=5.

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: use Math.max(i,j) instead of if-else — see Example 3.

2. Pattern Series Base

Foundation for concentric layouts, symmetric grids, and distance-based rules.

Example: swap max for min(i,j) to explore a different shape.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap numbers for letters or stars once the max rule works.

Example: print row numbers with leading spaces for alignment.

5. Complexity Intuition

Grid totals make O(k²) concrete for beginners.

Example: count values for k=5 → 5 rows × 9 values = 45 prints.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

Example: reject k <= 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 Java courses.

  1. 1. Instant Visual Feedback

    Wrong mirror bounds (starting right half at 1) duplicate the center value.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Change k, swap max for min, or mirror rows below for a full square.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-condition grid first; then try the Math.max compact in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use k for the outer bound and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

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

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    Compact: System.out.print(Math.max(i, j) + " "); in both inner loops inside the inner loop.

  5. 5. Dry-Run One Small n

    Trace k = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of numbers per line, you almost certainly put System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break concentric number square patterns.

  1. 1. System.out.println() Inside the Inner Loop

    Each number lands on its own line — you get a column, not a symmetric row.

    → Use System.out.print for each value; System.out.println() only after both inner loops finish.

  2. 2. Wrong Right-Half Start

    Starting the right loop at j = 1 prints the center twice on every row.

    → Keep for (j = 2; j <= k; j++) so the center appears once.

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every row onto one endless line.

    → Always end the row after both inner loops complete.

  4. 4. Unchecked Scanner input

    Letters or empty input throw InputMismatchException.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Hard-coding 5 everywhere

    Using literal 5 in loop bounds instead of variable k breaks dynamic input.

    → Use one k variable for the outer bound and both inner loops.

Edge Cases

Check these inputs before calling the solution done.

k = 1

Single row

Output is one row of 2k-1 numbers; for k=1 you get a single 1.

k = 0

Empty pattern

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

Negative

k < 0

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

Large n

Large k

Output grows with k rows and 2k-1 values per row — fine for labs, noisy for huge k.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves k unset — call sc.hasNextInt() first.

Compact

Math.max form

Use Math.max(i,j) for cleaner code — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change k

  • Try k = 3, 4, or 6
  • Count 2k-1 values per row

2. Use min instead of max

  • Replace max with min(i,j) for a different shape
  • Compare output side by side

3. Trim trailing spaces

  • Build each row with StringBuilder
  • Trim the final space before printing

4. Next in series

  • Continue with Program 47 full concentric diamond
  • Mirror rows below the center

Notes

  • Value count. Total numbers printed ≈ k×(2k-1) (e.g. 5×9 = 45 for k=5).
  • print stays on the line; println advances — mix them carefully.
  • Validate k > 0 for interactive programs; k = 1 prints one value.
  • Right half must start at j = 2 so the center value is not duplicated.

Quick Takeaway: set k, loop i = k..1, print max(i,j) for left and right halves, then break the row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(k²)O(1)
Math.max compact (Example 3)O(k²)O(1)
Wrap Up

🎉 Conclusion

The concentric number square pattern combines nested loops with a simple grid fill pattern — a natural step after concentric layouts. Master the fixed-k version first, then try user input and the Math.max compact form in Example 3.

Practice the three examples above, then continue to Program 47 for the concentric number diamond pattern.

Every cell uses print — keep println() only after the inner column loop finishes.

💡 Best Practices

✅ Do

  • Explain main diagonal, anti-diagonal, and left + right halves before coding
  • Use print(max(i,j) + " ") and println() after both inner loops
  • Validate k ≥ 1 for interactive programs
  • Check Scanner return value before using k
  • State O(k²) time when asked about complexity

❌ Don’t

  • Call System.out.println() between left and right halves (mid-row break)
  • Start the right half at j = 1 (duplicates center)
  • Hard-code 5 instead of variable k
  • Ignore bad console input in user-facing demos
  • Skip the k = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this concentric number square pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Left half

j = k..1

Code
03

Right half

j = 2..k

Logic
n 04

Values per row

2k-1

I/O
O 05

Complexity

O(k²)

Analysis

❓ Frequently Asked Questions

Because k=5 is the maximum. On any row i, column values near the edges use j when j>i, so the outer columns stay at k.
For row i and column j, the program prints j when j>i; otherwise i. That is equivalent to max(i, j).
When i=1, every j>1 prints j, but j=1 prints 1 at the center — creating the full symmetric sequence.
Yes. Replace k=5 with any positive integer. You get k rows and 2k-1 values per row.
This tutorial prints the top k rows (concentric-style). A full square often mirrors rows below the center too — see Program 47.
Yes. System.out.print(Math.max(i, j) + " ") works — see Example 3.
O(k²) because k rows each print about 2k-1 values.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Each cell prints max(i, j) — the left half loops j = k..1, the right half mirrors with j = 2..k. The smallest value appears at the center of the last row.

Continue to Program 47

Move on to the concentric number diamond pattern in the Java number-pattern series.

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