How to print Hollow Diamond Pattern in Swift


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,

  1. We define the number of rows for the diamond pattern.
  2. We use two nested loops, where the outer loop manages the rows and the inner loop controls the spaces and asterisks.
  3. Within the loops, we use conditions to determine when to print spaces and asterisks to achieve the hollow diamond effect.
  4. The outer loop increments and decrements based on the midpoint of the diamond pattern.
  5. The inner loop calculates the number of spaces required to position the asterisks correctly.
  6. 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

  1. How to print Left Half Pyramid Pattern in Swift ?
  2. How to print Right Half Pyramid Pattern in Swift ?
  3. How to print Pyramid Pattern in Swift ?
  4. How to print Rhombus Pattern in Swift ?
  5. How to print Diamond Pattern in Swift ?
  6. How to print Hour Glass Pattern in Swift ?
  7. How to print Hollow Square Pattern in Swift ?
  8. How to print Hollow Pyramid Pattern in Swift ?
  9. How to print Hollow Inverted Pyramid Pattern in Swift ?
  10. How to print Hollow Diamond Pattern in Swift ?
  11. How to print Floyd's Trianlge Pattern in Swift ?
  12. How to print Pascal's Triangle Pattern in Swift ?