0
0
Kotlinprogramming~10 mins

For loop with ranges in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop with ranges
Start
Set range start..end
For each value in range
Execute loop body
Next value in range?
NoExit loop
Back to Execute loop body
The loop starts by defining a range, then runs the loop body for each value in that range, moving to the next value until the end.
Execution Sample
Kotlin
for (i in 1..3) {
    println(i)
}
Prints numbers 1, 2, and 3 using a for loop over a range.
Execution Table
IterationiCondition (i in 1..3)ActionOutput
11truePrint i1
22truePrint i2
33truePrint i3
44falseExit loop
💡 Next value would be 4, which is outside the range 1..3, so the loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-1233
Key Moments - 2 Insights
Why does the loop stop before i becomes 4?
Because the range is from 1 to 3, and 4 is outside this range, so the condition i in 1..3 becomes false before assigning i=4 (see execution_table row 4).
Is the last value in the range included in the loop?
Yes, the range 1..3 includes 3, so the loop runs when i is 3 (see execution_table row 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the second iteration?
A2
B3
C1
D4
💡 Hint
Check the 'i' column in the execution_table at iteration 2.
At which iteration does the loop condition become false?
A3
B4
C1
D2
💡 Hint
Look at the 'Condition' column in the execution_table where it changes to false.
If the range was changed to 1..4, how many times would the loop run?
A3 times
B5 times
C4 times
D2 times
💡 Hint
The loop runs once for each number in the range, including the last number.
Concept Snapshot
for (variable in start..end) {
    // code to repeat
}

- Runs loop from start to end inclusive
- 'variable' takes each value in the range
- Loop stops after end value
- Simple way to repeat code fixed times
Full Transcript
This visual shows how a Kotlin for loop with a range works. The loop starts by setting a range from 1 to 3. Then, for each number in this range, it runs the loop body which prints the current number. The variable i takes values 1, 2, and 3 in order. After i=3, the next value 4 is outside the range, so the loop stops. This example helps beginners see how the loop variable changes and when the loop ends.