⚡ TL;DR
Print the concentric number square pattern in Swift with working code and output. Full implementation, sample run, and complexity analysis included.
The Concentric Number Square pattern is a classic loop exercise. Here’s the complete implementation in Swift with working code and output.
Pattern to Print
5 5 5 5 5
5 4 4 4 5
5 4 3 4 5
5 4 4 4 5
5 5 5 5 5Implementation
func concentricNumberSquare(_ n: Int) {
for i in 0..<n {
var row: [String] = []
for j in 0..<n {
let d = min(i, j, n - 1 - i, n - 1 - j)
row.append(String(n - d))
}
print(row.joined(separator: " "))
}
}
concentricNumberSquare(5)Output
5 5 5 5 5
5 4 4 4 5
5 4 3 4 5
5 4 4 4 5
5 5 5 5 5How It Works
For each cell, take the minimum distance to the four borders — that is its ring number d. The value n − d is largest in the center ring and repeats outward, so the grid becomes a set of nested number rings.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(n²) — the grid is stored before printing
FAQ
How do you print the Concentric Number Square pattern in Swift?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Swift implementation with expected output is shown in the sections above.
What is the time complexity of the Concentric Number Square pattern in Swift?
The time complexity is O(n²) and the space complexity is O(n²), since the pattern is built on a grid that is filled first and then printed row by row.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →