How to print Hour Glass Pattern in Kotlin


How to print Hour Glass Pattern in Kotlin ?

Answer

To print an Hourglass Pattern in Kotlin, we use nested loops. The outer loop controls the rows and the inner loops control the spaces and stars (*) to form the pattern.



✐ Examples

1 Hourglass Pattern with Specified Number of Rows

In this example,

  1. We define a function printHourglass that takes the desired number of rows n as a parameter.
  2. We use two nested for loops, where the first outer loop runs from n to 1 to print the upper part of the hourglass and the second outer loop runs from 2 to n to print the lower part of the hourglass.
  3. Within the inner loops, we calculate the number of spaces and stars based on the current row number to form the hourglass pattern.
  4. The repeat function is used to generate the required number of spaces and stars for each row.
  5. Finally, we print the combined string of spaces and stars for each row to standard output.

Kotlin Program

fun printHourglass(n: Int) {
    for (i in n downTo 1) {
        val spaces = " ".repeat(n - i)
        val stars = "*".repeat(2 * i - 1)
        println(spaces + stars)
    }
    for (i in 2..n) {
        val spaces = " ".repeat(n - i)
        val stars = "*".repeat(2 * i - 1)
        println(spaces + stars)
    }
}

fun main() {
    printHourglass(5)
}

Output

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

Summary

In this tutorial, we learned How to print Hour Glass 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 ?