How to print Hollow Square Pattern in Kotlin


How to print Hollow Square Pattern in Kotlin ?

Answer

To print a Hollow Square Pattern in Kotlin, we use nested loops. The outer loop controls the rows, and the inner loops control the columns and the conditions for printing the hollow square pattern.



✐ Examples

1 Hollow Square Pattern

In this example,

  1. We define a function printHollowSquare that takes the size of the square n as a parameter.
  2. We use two nested for loops to iterate over rows and columns.
  3. Within the loops, we check if we are at the first or last row or column, or if the current position is on the border of the square. If so, we print a star (*); otherwise, we print a space.

Kotlin Program

fun printHollowSquare(n: Int) {
    for (i in 0 until n) {
        for (j in 0 until n) {
            if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
                print("*")
            else
                print(" ")
        }
        println()
    }
}

// Example usage
fun main() {
    printHollowSquare(5)
}

Output

*****
*   *
*   *
*   *
*****

Summary

In this tutorial, we learned How to print Hollow Square Pattern in Kotlin language with well detailed examples.




More Kotlin Pattern Printing Tutorials

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