0
0
Kotlinprogramming~10 mins

For loop with step and downTo in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop with step and downTo
Initialize i = start
Check: i >= end?
NoEXIT
Yes
Execute loop body
Update: i = i - step
Back to Check
The loop starts at a number and counts down to an end number, decreasing by a step each time, running the loop body while the condition is true.
Execution Sample
Kotlin
for (i in 10 downTo 2 step 2) {
    println(i)
}
Prints numbers from 10 down to 2, decreasing by 2 each time.
Execution Table
Iterationi valueCondition (i >= 2)ActionOutput
110TruePrint 1010
28TruePrint 88
36TruePrint 66
44TruePrint 44
52TruePrint 22
💡 After printing 2, the next value would be 0 which is less than 2, so the loop stops.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
i108642
Key Moments - 2 Insights
Why does the loop stop when i is 0 even though 0 is less than 2?
The loop condition is i >= 2. When i becomes 0, 0 >= 2 is false, so the loop stops as shown in execution_table after the last printed value.
How does the step 2 affect the values of i?
The step 2 means i decreases by 2 each time (10, 8, 6, ...). This is shown in variable_tracker where i changes by -2 each iteration.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at iteration 3?
A8
B6
C4
D2
💡 Hint
Check the 'i value' column at iteration 3 in the execution_table.
At which iteration does the loop condition become false?
A5
B4
C6
D7
💡 Hint
Look at the 'Condition' column in execution_table where it becomes False.
If the step was changed to 3, what would be the value of i at iteration 2?
A7
B6
C5
D8
💡 Hint
With step 3, i decreases by 3 each time: 10, 7, 4... Check variable_tracker logic.
Concept Snapshot
for (i in start downTo end step stepValue) {
  // loop body
}

- Counts down from start to end (inclusive)
- Decreases i by stepValue each time
- Stops when i < end
- Useful for reverse loops with custom steps
Full Transcript
This visual execution shows how a Kotlin for loop with downTo and step works. The loop starts at 10 and counts down to 2, decreasing by 2 each time. Each iteration checks if i is still greater or equal to 2. If yes, it runs the loop body and prints i. Then i decreases by 2. When i becomes less than 2, the condition fails and the loop stops. The variable tracker shows i's value after each iteration. Key moments clarify why the loop stops and how step affects i. The quiz tests understanding of i's values and loop stopping point.