The for loop
- Kotlin course
- Beginner
- Lesson 42/116
- 4 min
Learn to write counted loops with for.
The for loop
The for loop runs a block multiple times. In Kotlin, for iterates over a range or a collection.
for (i in 1..5) {
println(i)
}This runs the block for each value of i from 1 to 5 (5 inclusive), printing 1, 2, 3, 4, 5. 1..5 is a range; you'll see it in detail later.
i is the loop variable and takes the next value each step. The loop ends when the range is exhausted.
for over a collection
for can also iterate over the items of a collection (for example, a list).
val fruits = listOf("apple", "pear", "cherry")
for (fruit in fruits) {
println(fruit)
}Here fruit takes one item from the list each step: first "apple", then "pear", then "cherry". You'll learn listOf later.
You don't need to write the loop variable's type; Kotlin infers it.
Practice Print 1 to 5
Write a fun main(). Use a for (i in 1..5) loop to call println(i). The output should be 1, 2, 3, 4, 5, each on its own line.
Starter code
fun main() {
// Print 1 to 5
}Sample solution
fun main() {
for (i in 1..5) {
println(i)
}
}Expected output
1 2 3 4 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many lines does for (i in 1..3) { println(i) } print?
- 3 lines Correct answer
- 2 lines
- 4 lines
- 1 line
Explanation: The 1..3 range has 3 values: 1, 2, 3.
2 Complete the for range
for (i in 1____5) { println(i) }
for (i in 1..5) { println(i) }
Explanation: The 1..5 range counts from 1 to 5 (5 inclusive).
3 Match the for forms
| Term | Meaning |
|---|---|
for (i in 1..5) |
Range loop |
for (item in list) |
List loop |
1..5 |
Range |
i |
Loop variable |