Kotlin – Star Pattern Programs

Kotlin – Star Pattern Programs

In Kotlin, star pattern programs involve printing various patterns using asterisks (*) in the console. These patterns can range from simple shapes like triangles and rectangles to more complex designs like pyramids and diamonds.

Examples

Example 1: Right Triangle Star Pattern

This example demonstrates how to print a right triangle star pattern.

Kotlin Program

fun main() {
    val rows = 5
    for (i in 1..rows) {
        for (j in 1..i) {
            print("* ")
        }
        println()
    }
}

Output

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

Example 2: Inverted Right Triangle Star Pattern

This example shows how to print an inverted right triangle star pattern.

Kotlin Program

fun main() {
    val rows = 5
    for (i in rows downTo 1) {
        for (j in 1..i) {
            print("* ")
        }
        println()
    }
}

Output

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

Example 3: Pyramid Star Pattern

This example illustrates printing a pyramid star pattern.

Kotlin Program


fun main() {
    val rows = 5
    var k = 0
    for (i in 1..rows) {
        for (space in 1..rows - i) {
            print("  ")
        }
        while (k != 2 * i - 1) {
            print("* ")
            ++k
        }
        k = 0
        println()
    }
}

Output

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

Example 4: Hollow Rectangle Star Pattern

This example demonstrates printing a hollow rectangle star pattern.

Kotlin Program

fun main() {
    val rows = 5
    val columns = 10
    for (i in 1..rows) {
        for (j in 1..columns) {
            if (i == 1 || i == rows || j == 1 || j == columns) {
                print("* ")
            } else {
                print("  ")
            }
        }
        println()
    }
}

Output

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

Example 5: Diamond Star Pattern

This example shows how to print a diamond star pattern.

Kotlin Program

fun main() {
    val rows = 5
    var space = rows - 1
    for (i in 1..rows) {
        for (j in 1..space) {
            print("  ")
        }
        space--
        for (j in 1..2 * i - 1) {
            print("* ")
        }
        println()
    }
    space = 1
    for (i in 1..rows - 1) {
        for (j in 1..space) {
            print("  ")
        }
        space++
        for (j in 1..2 * (rows - i) - 1) {
            print("* ")
        }
        println()
    }
}

Output

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

Summary

Star pattern programs in Kotlin involve using loops to print various patterns of asterisks (*) in the console. These patterns can range from simple shapes to more complex designs, providing a fun and educational way to explore programming concepts like loops and conditions.