Lesson 7 of 17

Loops

Loops in Kotlin

for loops

Iterate over a range with ..:

for (i in 1..5) {
    println(i)   // prints 1, 2, 3, 4, 5
}

Use until to exclude the upper bound:

for (i in 0 until 5) {
    println(i)   // prints 0, 1, 2, 3, 4
}

Iterate over a collection:

val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}

while loops

var n = 1
while (n <= 3) {
    println(n)
    n += 1
}

Your Turn

Use a for loop over the range 1..5 to compute and print the sum of squares (1 + 4 + 9 + 16 + 25 = 55).

JS Transpiler loading...
Loading...
Click "Run" to execute your code.