How to print Hollow Diamond Pattern in Swift - Step by Step Examples
How to print Hollow Diamond Pattern in Swift ?
Answer
To print a hollow diamond pattern in Swift, we use nested loops to control the printing of spaces and asterisks.
✐ Examples
1 Print Hollow Diamond Pattern in Swift
In this example,
- We define the number of rows for the diamond pattern.
- We use two nested loops, where the outer loop manages the rows and the inner loop controls the spaces and asterisks.
- Within the loops, we use conditions to determine when to print spaces and asterisks to achieve the hollow diamond effect.
- The outer loop increments and decrements based on the midpoint of the diamond pattern.
- The inner loop calculates the number of spaces required to position the asterisks correctly.
- We print asterisks based on specific conditions to create the hollow diamond pattern.
Swift Program
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)
Output
* * * * * * * * * * * * * * * *
Summary
In this tutorial, we learned How to print Hollow Diamond Pattern in Swift language with well detailed examples.
More Swift Pattern Printing Tutorials
- How to print Left Half Pyramid Pattern in Swift ?
- How to print Right Half Pyramid Pattern in Swift ?
- How to print Pyramid Pattern in Swift ?
- How to print Rhombus Pattern in Swift ?
- How to print Diamond Pattern in Swift ?
- How to print Hour Glass Pattern in Swift ?
- How to print Hollow Square Pattern in Swift ?
- How to print Hollow Pyramid Pattern in Swift ?
- How to print Hollow Inverted Pyramid Pattern in Swift ?
- How to print Hollow Diamond Pattern in Swift ?
- How to print Floyd's Trianlge Pattern in Swift ?
- How to print Pascal's Triangle Pattern in Swift ?