Kotlin for Loop
A for loop repeats a block of code for each item in a sequence. Instead of writing the same instruction ten times, you write it once inside a loop and tell Kotlin how many times to repeat it.
for Loop with a Range
for (i in 1..5) {
println(i)
}Output:
1
2
3
4
5How the Range Works
1..5 means: start at 1, go up to and including 5
┌──┬──┬──┬──┬──┐
│1 │2 │3 │4 │5 │
└──┴──┴──┴──┴──┘
i takes each value, one at a time, left to right
Exclusive Upper Bound with until
for (i in 1 until 5) {
println(i)
}
// Output: 1 2 3 4 (5 is NOT included)Counting Down with downTo
for (i in 5 downTo 1) {
println(i)
}
// Output: 5 4 3 2 1Step: Skip Values
for (i in 0..20 step 5) {
println(i)
}
// Output: 0 5 10 15 20
for (i in 10 downTo 0 step 3) {
print("$i ")
}
// Output: 10 7 4 1Looping Over a List
val fruits = listOf("Apple", "Mango", "Banana", "Grape")
for (fruit in fruits) {
println(fruit)
}Output:
Apple
Mango
Banana
GrapeLooping with Index
Use withIndex() when you need both the position and the value:
val cities = listOf("Delhi", "Mumbai", "Chennai")
for ((index, city) in cities.withIndex()) {
println("$index: $city")
}Output:
0: Delhi
1: Mumbai
2: ChennaiLooping Over a String
val word = "Kotlin"
for (ch in word) {
print("$ch-")
}
// Output: K-o-t-l-i-n-Looping Over a Map
val scores = mapOf("Alice" to 92, "Bob" to 88, "Carol" to 95)
for ((name, score) in scores) {
println("$name scored $score")
}Output:
Alice scored 92
Bob scored 88
Carol scored 95Nested for Loops
for (row in 1..3) {
for (col in 1..3) {
print("($row,$col) ")
}
println()
}Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)Practical Example: Multiplication Table
fun main() {
val number = 7
println("Multiplication Table of $number")
println("──────────────────────────")
for (i in 1..10) {
println("$number × $i = ${number * i}")
}
}Output:
Multiplication Table of 7
──────────────────────────
7 × 1 = 7
7 × 2 = 14
7 × 3 = 21
7 × 4 = 28
7 × 5 = 35
7 × 6 = 42
7 × 7 = 49
7 × 8 = 56
7 × 9 = 63
7 × 10 = 70