In this post, we can try interesting pattern printing challenge in Swift. The problem statement goes like this "Print a staircase of given size 'n'. Make sure that its base and height are both equal to n, and the image is drawn only using `#` symbols and spaces. The last line is not preceded by any spaces."
Expected Output :
# | |
## | |
### | |
#### | |
##### | |
###### |
Working solution:
func makePatternOf(_ size: Int) {
var str = ""
// 1
for index in (0..<size) {
let stop = size-index-1;
// 2
for _ in 0..<stop {
str.append(" ");
}
// 3
for _ in 0...index {
str.append("#");
}
print(str)
str = ""
}
}
makePatternOf(6)
- Loop to visit every row of stair case.
- Loop for appending spaces until the limit of empty space.
- Final loop for simply append the # pattern.
We can try couple of other variants like Piramid, Mirrored patterns as bonus challenge. Thanks for reading & happy coding.