Kotlin For Loop

Iterating through ranges and collections

🔄 What is For Loop?

For loop is the most versatile loop in Kotlin, perfect for iterating through ranges, collections, and arrays. It automatically handles the iteration logic, making your code cleaner and more readable than manual counting.


// Basic for loop
for (i in 1..5) {
    println("Step $i")
}
                                    

For Loop Variations

📊

Range Loop

Iterate through number ranges

for (i in 1..10) {
    println(i)
}
📋

Collection Loop

Iterate through lists and arrays

val list = listOf("A", "B", "C")
for (item in list) {
    println(item)
}
🔢

Step Loop

Skip numbers with step

for (i in 0..10 step 2) {
    println(i) // 0, 2, 4, 6, 8, 10
}
⬇️

Reverse Loop

Count backwards

for (i in 10 downTo 1) {
    println(i)
}

🔹 Basic Range Loop

Iterate through a range of numbers:

fun main() {
    // Print numbers 1 to 5
    println("Counting from 1 to 5:")
    for (number in 1..5) {
        println("Number: $number")
    }
    
    // Calculate sum
    var sum = 0
    for (i in 1..10) {
        sum += i
    }
    println("\nSum of 1 to 10: $sum")
}

Output:

Counting from 1 to 5:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5


Sum of 1 to 10: 55

🔹 Looping Through Collections

Iterate through lists, arrays, and other collections:

fun main() {
    val colors = listOf("Red", "Green", "Blue", "Yellow")
    val scores = arrayOf(85, 92, 78, 96, 88)
    
    // Loop through list
    println("Available colors:")
    for (color in colors) {
        println("🎨 $color")
    }
    
    // Loop through array with processing
    println("\nStudent scores:")
    for (score in scores) {
        val grade = when {
            score >= 90 -> "A"
            score >= 80 -> "B"
            score >= 70 -> "C"
            else -> "F"
        }
        println("Score: $score (Grade: $grade)")
    }
}

Output:

Available colors:

🎨 Red

🎨 Green

🎨 Blue

🎨 Yellow


Student scores:

Score: 85 (Grade: B)

Score: 92 (Grade: A)

Score: 78 (Grade: C)

Score: 96 (Grade: A)

Score: 88 (Grade: B)

🔹 Loop with Index

Get both the item and its position:

fun main() {
    val fruits = listOf("Apple", "Banana", "Orange")
    
    // Using withIndex()
    println("Shopping list:")
    for ((index, fruit) in fruits.withIndex()) {
        println("${index + 1}. $fruit")
    }
    
    // Using indices property
    println("\nUsing indices:")
    for (i in fruits.indices) {
        println("Item $i: ${fruits[i]}")
    }
    
    // Manual indexing
    println("\nManual counting:")
    var position = 1
    for (fruit in fruits) {
        println("Position $position: $fruit")
        position++
    }
}

Output:

Shopping list:

1. Apple

2. Banana

3. Orange


Using indices:

Item 0: Apple

Item 1: Banana

Item 2: Orange


Manual counting:

Position 1: Apple

Position 2: Banana

Position 3: Orange

🔹 Step and Reverse Loops

Control the iteration pattern:

fun main() {
    // Step loop - skip numbers
    println("Even numbers from 0 to 10:")
    for (i in 0..10 step 2) {
        println(i)
    }
    
    // Reverse loop
    println("\nCountdown:")
    for (i in 5 downTo 1) {
        println("$i...")
    }
    println("🚀 Launch!")
    
    // Reverse with step
    println("\nEvery 3rd number backwards:")
    for (i in 15 downTo 0 step 3) {
        println(i)
    }
}

Output:

Even numbers from 0 to 10:

0

2

4

6

8

10


Countdown:

5...

4...

3...

2...

1...

🚀 Launch!


Every 3rd number backwards:

15

12

9

6

3

0

🔹 Nested For Loops

Loop inside another loop:

fun main() {
    // Multiplication table
    println("Multiplication Table (1-5):")
    for (i in 1..5) {
        for (j in 1..5) {
            print("${i * j}\t")
        }
        println() // New line after each row
    }
    
    // Pattern printing
    println("\nStar pattern:")
    for (row in 1..4) {
        for (star in 1..row) {
            print("⭐")
        }
        println()
    }
}

Output:

Multiplication Table (1-5):

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

4 8 12 16 20

5 10 15 20 25


Star pattern:

⭐⭐

⭐⭐⭐

⭐⭐⭐⭐

🧠 Test Your Knowledge

What does for (i in 2..8 step 2) print?