KOTLIN Tutorial



CONTROL FLOW IN KOTLIN


Control Flow in Kotlin

Control flow statements in Kotlin allow you to control the execution order of code. Kotlin includes standard conditional and looping structures like if, when, for, while, and do..while.

1. if, else if, else

Used to make decisions based on conditions.

fun main() {
    val number = 10

    if (number > 0) {
        println("Positive")
    } else if (number < 0) {
        println("Negative")
    } else {
        println("Zero")
    }
}
  

2. if as an Expression

if can return a value directly.

fun main() {
    val a = 5
    val b = 10
    val max = if (a > b) a else b
    println("Max: $max")
}
  

3. when Expression

when is Kotlin’s alternative to switch in other languages.

fun main() {
    val day = 3

    val result = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        6, 7 -> "Weekend"
        else -> "Invalid day"
    }

    println(result)
}
  

4. for Loop

Used to iterate over a range, array, or collection.

fun main() {
    for (i in 1..5) {
        println("i = $i")
    }

    val fruits = listOf("Apple", "Banana", "Mango")
    for (fruit in fruits) {
        println(fruit)
    }
}
  

5. while Loop

Repeats a block of code while a condition is true.

fun main() {
    var i = 1
    while (i <= 5) {
        println("i = $i")
        i++
    }
}
  

6. do..while Loop

Similar to while but guarantees at least one execution.

fun main() {
    var i = 1
    do {
        println("i = $i")
        i++
    } while (i <= 5)
}
  

7. break and continue

break exits the loop, continue skips to the next iteration.

fun main() {
    for (i in 1..5) {
        if (i == 3) continue
        if (i == 5) break
        println(i)
    }
}
  

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review