Unlike Program 46 (top half only), here a second outer loop completes the diamond.
Approach
How to Solve It
Print rows for i = k..1, then repeat the same row logic for i = 2..k.
Method
Idea
Best for
Two outer halves
Top k..1, bottom 2..k; each row uses max(i, j)
Learning, interviews, exams
printRow helper
One method for both halves — same output, less duplication
Cleaner code once the row rule is clear
Pseudocode
Pseudocode
for i from k down to 1: // top
print row for i
for i from 2 to k: // bottom
print row for i
print row for i:
for j from k down to 1: print max(i, j)
for j from 2 to k: print max(i, j)
print newline
Cheat sheet
Goal
Pattern
Top half
for (int i = k; i >= 1; i--)
Bottom half
for (int i = 2; i <= k; i++)
Left / right
j = k..1 then j = 2..k
Cell value
j > i ? j : i or Math.max(i, j)
Total size
2k − 1 rows and columns
Printing Numbers vs Starting a New Line
API
Effect
Use for
System.out.print
Stays on the same line
Each number (with a trailing space)
System.out.println
Ends the current line
After both half-loops of a row finish
Print values without a newline, then end the row once.
Try it
Live Preview
Change k and the concentric diamond updates instantly.
Whole numbers from 2 to 5 (keeps the full diamond readable). Tap a chip or type a value — the preview redraws as you go.
1. Prompt and guard. Read k; exit early if it is less than 1.
2. Same core. Only the source of k changes from a literal to user input.
3. Safer input tip. Prefer:
Safer input
if (!sc.hasNextInt()) {
System.out.println("Enter a positive integer.");
return;
}
int k = sc.nextInt();
if (k < 1) {
System.out.println("Enter a positive integer.");
return;
}
Example 3 — printRow Helper
One printRow(i, k) method — both outer loops call it.
Java
public class ConcentricNumberDiamondHelper {
static void printRow(int i, int k) {
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();
}
public static void main(String[] args) {
int k = 5;
for (int i = k; i >= 1; i--)
printRow(i, k);
for (int i = 2; i <= k; i++)
printRow(i, k);
}
}