Kotlin Control Flow

Control flow determines which lines of code run and when. Without it, every program would execute every line from top to bottom with no decisions and no repetition. Control flow gives your program the ability to choose and repeat.

if / else — Making Decisions

The if statement checks a condition. If the condition is true, it runs one block of code. If false, it runs another.

val temperature = 38

if (temperature > 37.5) {
    println("You have a fever.")
} else {
    println("Your temperature is normal.")
}
// Output: You have a fever.

if as an Expression

In Kotlin, if can return a value. You can store the result directly in a variable.

val marks = 72
val grade = if (marks >= 90) "A" else if (marks >= 75) "B" else "C"
println(grade)   // C

when — Kotlin's Powerful Switch

The when statement replaces long chains of if-else if. Think of it like a menu — you check one value against many options.

val day = 3

when (day) {
    1 -> println("Monday")
    2 -> println("Tuesday")
    3 -> println("Wednesday")
    4 -> println("Thursday")
    5 -> println("Friday")
    6, 7 -> println("Weekend")
    else -> println("Invalid day")
}
// Output: Wednesday

when With Ranges and Conditions

val score = 85

when {
    score >= 90 -> println("Grade: A")
    score >= 80 -> println("Grade: B")
    score >= 70 -> println("Grade: C")
    else        -> println("Grade: F")
}
// Output: Grade: B

when as an Expression

val season = "July"
val weather = when (season) {
    "December", "January" -> "Cold"
    "April", "May"        -> "Hot"
    "July", "August"      -> "Rainy"
    else                  -> "Mild"
}
println(weather)   // Rainy

for Loop — Repeating Over a Range

The for loop runs a block of code for each item in a sequence.

// Loop from 1 to 5
for (i in 1..5) {
    println("Count: $i")
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5

Diagram — for Loop Execution

i = 1 → print "Count: 1"
i = 2 → print "Count: 2"
i = 3 → print "Count: 3"
i = 4 → print "Count: 4"
i = 5 → print "Count: 5"
i = 6 → 6 > 5, loop ends

for Loop Variations

// Count down
for (i in 5 downTo 1) { print("$i ") }
// Output: 5 4 3 2 1

// Skip every other number (step)
for (i in 0..10 step 2) { print("$i ") }
// Output: 0 2 4 6 8 10

// Loop through a list
val fruits = listOf("Apple", "Mango", "Banana")
for (fruit in fruits) {
    println(fruit)
}

while Loop — Repeating While a Condition is True

The while loop keeps running as long as its condition stays true. It first checks the condition, then runs the block.

var battery = 100

while (battery > 20) {
    println("Battery: $battery%")
    battery -= 10
}
println("Low battery warning!")

// Output:
// Battery: 100%
// Battery: 90%
// ...
// Battery: 30%
// Low battery warning!

Diagram — while vs do-while

while loop:
┌──────────────┐
│ Check        │ ← condition checked FIRST
│ condition    │
└──────┬───────┘
       │ true
       v
  [Run block]
       │
       └── loop back to check

do-while loop:
  [Run block]   ← block runs FIRST
       │
       v
┌──────────────┐
│ Check        │ ← condition checked AFTER
│ condition    │
└──────────────┘
  if true → loop back

do-while Loop

The do-while loop always runs the block at least once, then checks the condition.

var pin = ""

do {
    print("Enter 4-digit PIN: ")
    pin = readLine() ?: ""
} while (pin.length != 4)

println("PIN accepted.")

break and continue

break stops the loop immediately. continue skips the current iteration and moves to the next one.

// break example
for (i in 1..10) {
    if (i == 5) break
    print("$i ")
}
// Output: 1 2 3 4

// continue example
for (i in 1..10) {
    if (i % 2 == 0) continue
    print("$i ")
}
// Output: 1 3 5 7 9

Labeled Loops — Breaking Out of Nested Loops

When you have a loop inside a loop, break only exits the inner loop. A label lets you break out of both at once.

outer@ for (row in 1..3) {
    for (col in 1..3) {
        if (col == 2) break@outer   // exits both loops
        print("($row,$col) ")
    }
}
// Output: (1,1)

Leave a Comment

Your email address will not be published. Required fields are marked *