Array loop
- Kotlin course
- Beginner
- Lesson 56/116
- 5 min
Learn to iterate over arrays with for.
Array loop
A for loop iterates over array elements in order. The for (item in array) form takes each element one by one.
val fruits = arrayOf("apple", "pear", "cherry")
for (fruit in fruits) {
println(fruit)
}
// apple, pear, cherryHere fruit represents one element each step. When you don't need the index, this form is the cleanest.
You don't need to write the loop variable's type; Kotlin infers it.
Practice Print all elements
Write a fun main(). Create an array with val fruits = arrayOf("apple", "pear", "cherry"). Use for (fruit in fruits) { println(fruit) } to print all elements.
Starter code
fun main() {
// Print all elements
}Sample solution
fun main() {
val fruits = arrayOf("apple", "pear", "cherry")
for (fruit in fruits) {
println(fruit)
}
}Expected output
apple pear cherry
Iterating by index
If you also need the index, iterate with arr.indices. The element is then taken with arr[i].
val nums = intArrayOf(3, 7, 2)
for (i in nums.indices) {
println("$i: ${nums[i]}")
}
// 0: 3, 1: 7, 2: 2Here both the index (i) and the element (nums[i]) are used. If you don't need the index, plain for (n in nums) is shorter.
Both forms are common; pick based on need.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the for loop
for (____ in fruits) { println(fruit) }
for (fruit in fruits) { println(fruit) }
Explanation: for (fruit in fruits) takes each element in turn.
2 What does for (fruit in fruits) { ... } do?
- Prints the indices
- Empties the array
- Takes each element in turn Correct answer
- Takes only the first element
Explanation: for-each visits each element one by one.
3 Match the loop forms
| Term | Meaning |
|---|---|
for (item in arr) |
By element |
for (i in arr.indices) |
By index |
arr[i] |
Index access |
item |
Element variable |