A concentric number square peels layers from outer value k down to 1 at the center. Each row mirrors left and right so the shape stays symmetric — width 2k - 1, height k (top half only).
if (!(cin >> k) || k < 1)
{
cout << "Please enter a positive integer.\n";
return 1;
}
Example 3 — Compact k = 3
Smaller outer value for quick tracing on paper or in interviews.
C++
#include <iostream>
using namespace std;
int main()
{
int k = 3;
int i, j;
for (i = k; i >= 1; i--)
{
for (j = k; j >= 1; j--)
cout << (j > i ? j : i) << " ";
for (j = 2; j <= k; j++)
cout << (j > i ? j : i) << " ";
cout << "\n";
}
return 0;
}
Output
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
How It Works
1. Only three rows. Easy to dry-run every j value by hand.
2. Same formula. Nothing changes except k — proving the pattern scales.
3. Center is always 1. The last row always ends with ... 1 ... when the loops finish at i = 1.
Edge Cases & Pitfalls
Check these before calling the solution done.
Right starts at 2
Do not start the right loop at 1
Starting at 1 duplicates the center cell. Use for (j = 2; j <= k; j++).
j > i
Do not swap the comparison
j > i picks the outer ring. Using j < i or i > j alone without care inverts the layers.
Bad cin
Validate input
Check cin >> k and require k >= 1 before the loops.
Spaces
Print a space after each value
Use cout << value << " " so columns stay readable and match the sample layout.
Analysis
Time and Space Complexity
Program
Time
Extra space
Nested layer loops (Examples 1–3)
O(k²)
O(1)
There are k rows and each prints 2k - 1 values, so work is quadratic in k. Only a few integers of extra memory.
Remember
Key Takeaways
Rule: print j when j > i, otherwise print i.
Two halves: left j = k..1, right j = 2..k — width 2k - 1.
Break the row: call cout << "\n" only after both inner loops.
Complexity:O(k²) time; O(1) extra space.
One line: for each layer i, print left then right with (j > i ? j : i), then end the line.
Frequently Asked Questions
A concentric number square where the outer layer is k (e.g. 5) and numbers decrease toward the center, ending with 1, then mirror back out on each row.
For the current layer i, if the column index j is greater than i, print j (outer ring); otherwise print i (fill the inner plateau).
The first walks left-to-center (j = k down to 1). The second walks center-to-right (j = 2 to k), skipping a second copy of the center cell.
Width is 2k - 1. For k = 5 the row has 9 numbers; for k = 3 it has 5.
Program 45 prints * and 0 on diagonals. Program 46 prints decreasing/increasing numbers in concentric layers.
Printing a number (and space) stays on the same line. Printing a newline ends the current line. Cells use cout without a newline; the row break uses cout << "\n" after both inner loops.
O(k²) because each of k rows prints 2k - 1 values.
After cin >> k, check failure and require k ≥ 1 before the loops.
🤔
Did you know?
Each row has width 2k - 1. The outer loop runs k times (i = k..1). Total prints = k × (2k - 1) — quadratic in k.