To print a hollow diamond pattern in Swift, we use nested loops to control the printing of spaces and asterisks.
In this example,
func printHollowDiamondPattern(size: Int) {
for i in 1...size {
for _ in 0..<(size - i) {
print(" ", terminator: "")
}
for _ in 0..<(2 * i - 1) {
if _ == 0 || _ == (2 * i - 2) {
print("*", terminator: "")
} else {
print(" ", terminator: "")
}
}
print()
}
for i in (1..<(size - 1)).reversed() {
for _ in 0..<(size - i) {
print(" ", terminator: "")
}
for _ in 0..<(2 * i - 1) {
if _ == 0 || _ == (2 * i - 2) {
print("*", terminator: "")
} else {
print(" ", terminator: "")
}
}
print()
}
}
// Call the function to print the hollow diamond pattern
printHollowDiamondPattern(size: 5)
* * * * * * * * * * * * * * * *
In this tutorial, we learned How to print Hollow Diamond Pattern in Swift language with well detailed examples.