0
0
Kotlinprogramming~10 mins

For loop over collections in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop over collections
Start
Get collection
Take first element
Execute loop body with element
More elements?
NoEnd
Yes
Take next element
The loop starts by getting the collection, then takes each element one by one, runs the loop body, and repeats until no elements remain.
Execution Sample
Kotlin
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}
This code loops over a list of fruits and prints each fruit.
Execution Table
Iterationfruit valueActionOutput
1"apple"Print fruitapple
2"banana"Print fruitbanana
3"cherry"Print fruitcherry
--No more elements, loop ends-
💡 All elements in the collection have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
fruitundefined"apple""banana""cherry"undefined
Key Moments - 2 Insights
Why does the variable 'fruit' change each iteration?
Because in each iteration, 'fruit' takes the next element from the collection, as shown in execution_table rows 1 to 3.
What happens when the loop reaches the last element?
After printing the last element, the loop checks for more elements, finds none, and ends (see last row in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'fruit' in iteration 2?
A"apple"
B"banana"
C"cherry"
Dundefined
💡 Hint
Check the 'fruit value' column in the second row of execution_table.
At which iteration does the loop stop running?
AAfter iteration 3
BAfter iteration 1
CAfter iteration 2
DIt never stops
💡 Hint
Look at the exit_note and the last row of execution_table.
If the collection had 4 elements, how would the execution_table change?
AThe output would be empty
BThe loop would stop after 3 iterations anyway
CThere would be 4 iterations with fruit values for each element
DThe loop would run infinitely
💡 Hint
Refer to how each element corresponds to one iteration in execution_table.
Concept Snapshot
For loop over collections in Kotlin:
for (item in collection) {
    // use item
}
Loops through each element in the collection one by one.
The loop variable takes each element in order.
Loop ends when all elements are processed.
Full Transcript
This visual execution shows how a Kotlin for loop works over a collection. The loop starts by getting the collection and then takes each element one by one. In each iteration, the loop variable 'fruit' holds the current element. The loop body prints the fruit. After the last element is processed, the loop ends. The variable tracker shows how 'fruit' changes each iteration. Key moments clarify why 'fruit' changes and when the loop stops. The quiz tests understanding of variable values and loop termination.