Chapter 7: Loops
Loops in Kotlin — this is the chapter where your programs start doing real work by repeating tasks efficiently and elegantly!
Kotlin has beautiful, clean, and very powerful loop constructs — much nicer than Java. We’ll cover everything super slowly, with real-life analogies, lots of copy-paste examples, step-by-step breakdowns, tables, common mistakes with fixes, and fun facts so it all sticks perfectly.
Grab your cutting chai ☕ — let’s dive in!
1. for Loop – The Most Beautiful Loop in Kotlin
Kotlin’s for loop is not like Java’s for (int i = 0; i < 10; i++) — it’s much more expressive and idiomatic.
Main forms of for loop:
| Type | Syntax Example | Use When |
|---|---|---|
| Range | for (i in 1..10) | Known count (numbers) |
| Until | for (i in 1 until 10) | Exclude the end |
| DownTo | for (i in 10 downTo 1) | Counting backwards |
| Step | for (i in 1..10 step 2) | Jump by step |
| Array / Collection | for (item in list) | Iterate over elements |
| With index | for ((index, value) in list.withIndex()) | Need both index & value |
A. Looping over ranges
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
fun main() { // 1. Simple range (inclusive) for (i in 1..5) { print("$i ") // 1 2 3 4 5 } println() // 2. Until (excludes 10) for (i in 1 until 10 step 2) { print("$i ") // 1 3 5 7 9 } println() // 3. DownTo (countdown) for (i in 10 downTo 1 step 2) { print("$i ") // 10 8 6 4 2 } println() } |
Fun fact: You can use downTo with step — very useful for reverse countdowns!
B. Looping over arrays & collections
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun main() { val cities = listOf("Mumbai", "Pune", "Delhi", "Bangalore", "Chennai") // Simple for-each style for (city in cities) { println("City: $city") } // With index (very common!) for ((index, city) in cities.withIndex()) { println("Position $index: $city") } // Or using indices for (i in cities.indices) { println("City at $i: {cities[i]}") } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
City: Mumbai City: Pune ... Position 0: Mumbai Position 1: Pune ... |
C. Looping over arrays with indices
|
0 1 2 3 4 5 6 7 8 9 10 |
val numbers = intArrayOf(10, 20, 30, 40, 50) for ((index, value) in numbers.withIndex()) { println("Index $index → Value $value") } |
2. while & do-while Loops
These are almost identical to Java — but cleaner.
while – check condition first
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { var count = 1 while (count <= 5) { println("Count: $count") count++ } } |
do-while – run at least once, then check condition
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
fun main() { var input: String do { println("तुमचं नाव सांगा (किंवा 'exit' लिहा):") input = readln() if (input != "exit") { println("नमस्ते $input!") } } while (input != "exit") println("धन्यवाद! बाय!") } |
3. Labels – @loop, break@loop, continue@loop
Kotlin allows labels on loops → you can break or continue a specific outer loop.
Real-life analogy: You’re in a big mall with many floors (nested loops). Normal break only takes you out of the current floor. With label → you can say “break@mall” → exit the entire mall!
Example – Nested loops with labels
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
fun main() { outer@ for (i in 1..5) { println("Outer loop: $i") for (j in 1..5) { println(" Inner: $j") if (j == 3) { println(" Breaking outer loop!") break@outer // Exit BOTH loops! } } } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
Outer loop: 1 Inner: 1 Inner: 2 Inner: 3 Breaking outer loop! |
With continue@label
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
outer@ for (i in 1..3) { for (j in 1..5) { if (j == 3) { continue@outer // Skip rest of inner & go to next outer } println("i=$i, j=$j") } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
i=1, j=1 i=1, j=2 i=2, j=1 i=2, j=2 i=3, j=1 i=3, j=2 |
4. return@label in Lambdas
Very powerful when you want to return from a lambda (not just continue/break).
Example – Find first even number in nested loops
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fun main() { val numbers = listOf(listOf(1,3,5), listOf(2,4,6), listOf(7,9)) run loop@{ numbers.forEach { row -> row.forEach { num -> if (num % 2 == 0) { println("Found even number: $num") return@loop // Exit the whole block! } } } println("No even numbers found") } } |
Output:
|
0 1 2 3 4 5 6 |
Found even number: 2 |
5. Quick Recap Table (Your Cheat Sheet)
| Loop Type | Syntax Example | Key Feature |
|---|---|---|
| for range | for (i in 1..10) | Inclusive range |
| for until | for (i in 1 until 10) | Excludes end |
| for downTo | for (i in 10 downTo 1) | Countdown |
| for collection | for (item in list) | Clean for-each |
| for with index | for ((i, v) in list.withIndex()) | Get index + value |
| while | while (condition) { … } | Check first |
| do-while | do { … } while (condition) | Run at least once |
| break@label | break@outer | Exit specific loop |
| return@label | return@loop | Return from lambda block |
6. Common Newbie Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| Writing for (i = 0; i < 10; i++) | Java style → compile error | Use for (i in 0 until 10) |
| Forgetting in keyword | for (i 1..10) → error | Always write in |
| Using break in nested loops | Only breaks inner loop | Use break@label |
| return inside lambda | Returns from lambda (not outer function) | Use return@label |
| Confusing .. and until | Off-by-one bugs | Remember: .. includes end |
7. Homework for You (Let’s Make It Fun!)
- Basic Print numbers 1 to 10 using for (i in 1..10)
- Medium Print even numbers from 1 to 20 using step 2
- Advanced Nested loop: print multiplication table 1 to 5 (1 × 1 = 1, 1 × 2 = 2, …, 5 × 5 = 25)
- Fun Ask user for a number N → print countdown from N to 1 using downTo
- Challenge Use labeled break to exit two nested loops when you find number 42 in a 5×5 grid.
You’ve just mastered Kotlin’s beautiful loops — now your programs can repeat tasks like a pro!
