KOTLIN Tutorial



LOOPS IN KOTLIN


Loops in Kotlin

Loops are used to execute a block of code multiple times. Kotlin provides several loop types to handle repetitive tasks efficiently.


1. for Loop

The for loop is used to iterate over ranges, arrays, or collections.

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

Output:
Count: 1
Count: 2
... up to 5

✍️ Try replacing 1..5 with 5 downTo 1 and add step 2 to skip numbers.

2. while Loop

Repeats a block of code while a condition is true.

fun main() {
    var x = 1
    while (x <= 3) {
        println("x is $x")
        x++
    }
}
  

Output:
x is 1
x is 2
x is 3


3. do...while Loop

This loop executes the block at least once before checking the condition.

fun main() {
    var y = 1
    do {
        println("y is $y")
        y++
    } while (y <= 2)
}
  

This will print y is 1 and y is 2.


4. Looping Through Arrays

Iterate directly through elements of a list or array.

fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")

    for (fruit in fruits) {
        println(fruit)
    }
}
  

Output:
Apple
Banana
Cherry


5. Loop with Index

You can get both element and index using withIndex().

fun main() {
    val colors = arrayOf("Red", "Green", "Blue")

    for ((index, value) in colors.withIndex()) {
        println("Index $index: $value")
    }
}
  
💡 Efficient for displaying list contents with their position.

6. Breaking & Continuing

Use break to exit a loop and continue to skip an iteration.

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

Output: 1, 2, 4 (3 is skipped, loop breaks at 5)


Summary

  • for — iterate over ranges, arrays
  • while — repeat while a condition is true
  • do...while — always runs at least once
  • break / continue — control the loop flow
✅ Practicing loops builds strong control-flow skills — experiment with conditions and ranges!

🌟 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