⚡ TL;DR
Print the hollow cross plus pattern in Swift. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Hollow Cross Plus pattern is a classic loop exercise. Here’s the complete implementation in Swift with working code and output.
Pattern to Print
* *
* *
*****
* *
* *Implementation
func hollowCross(_ n: Int) {
let mid = n / 2
for i in 0..<n {
var row = ""
for j in 0..<n { row += (i == mid || j == 0 || j == n - 1) ? "*" : " " }
print(row)
}
}
hollowCross(5)Output
* *
* *
*****
* *
* *How It Works
Middle row solid, sides are vertical bars with hollow interior.
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(1) — only loop counters are needed
Related Patterns
- Hollow Cross Plus in Python
- Hollow Cross Plus in Dart
- Hollow Cross Plus in Go
- Right-Facing Arrowhead in Swift
- Framed Triangle in Swift
- Inverted Number Hourglass in Swift
FAQ
How do you print the Hollow Cross Plus 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 Hollow Cross Plus pattern in Swift?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
