To print an Hourglass Pattern in Swift, we use nested loops. The outer loop controls the rows and the inner loops control the spaces and stars (*) to form the pattern.
In this example,
printHourglass
that takes the desired number of rows n
as a parameter.for
loops, where the outer loop runs from n
to 1 and the inner loops control the spaces and stars in each row.func printHourglass(_ n: Int) {
for i in stride(from: n, to: 0, by: -1) {
let spaces = String(repeating: " ", count: n - i)
let stars = String(repeating: "*", count: 2 * i - 1)
print(spaces + stars)
}
for i in 2...n {
let spaces = String(repeating: " ", count: n - i)
let stars = String(repeating: "*", count: 2 * i - 1)
print(spaces + stars)
}
}
// Example usage
printHourglass(5)
********* ******* ***** *** * *** ***** ******* *********
In this tutorial, we learned How to print Hour Glass Pattern in Swift language with well detailed examples.