0
0
Kotlinprogramming~10 mins

While and do-while loops in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While and do-while loops
Initialize counter
Check condition
Execute body
Update counter
Back to Check
The loop starts by checking a condition. If true, it runs the code inside, updates variables, then checks again. If false, it stops.
Execution Sample
Kotlin
var i = 1
while (i <= 3) {
  println(i)
  i++
}

var j = 1
do {
  println(j)
  j++
} while (j <= 3)
This code prints numbers 1 to 3 using a while loop and then again using a do-while loop.
Execution Table
StepVariable iCondition i <= 3ActionOutput
11truePrint i=1, i++1
22truePrint i=2, i++2
33truePrint i=3, i++3
44falseExit loop
💡 i reaches 4, condition 4 <= 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i12344
j12344
Key Moments - 2 Insights
Why does the while loop sometimes not run at all?
Because the condition is checked before the loop body. If false at start (see Step 4 in execution_table), the loop body never runs.
Why does the do-while loop always run at least once?
Because the loop body runs first, then the condition is checked. So even if condition is false initially, body runs once.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at Step 3?
A4
B2
C3
D1
💡 Hint
Check the 'Variable i' column at Step 3 in execution_table
At which step does the while loop stop running?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the 'Condition i <= 3' column and see when it becomes false
If the initial value of i was 5, what would happen to the while loop?
AIt does not run at all
BIt runs once
CIt runs three times
DIt runs infinitely
💡 Hint
Refer to key_moments about condition checked before loop body
Concept Snapshot
while (condition) {
  // code runs while condition is true
}

- Condition checked before loop body
- May run zero or more times

do {
  // code runs at least once
} while (condition)

- Condition checked after loop body
- Runs one or more times
Full Transcript
This lesson shows how while and do-while loops work in Kotlin. The while loop checks the condition first. If true, it runs the code inside and updates variables, then checks again. If false, it stops immediately. The do-while loop runs the code first, then checks the condition. This means do-while always runs at least once. We traced a simple example printing numbers 1 to 3. The variable i starts at 1 and increases each loop. The while loop stops when i becomes 4 because 4 <= 3 is false. Key points: while loop may not run if condition is false at start; do-while runs once no matter what. The quiz asks about variable values and loop stopping points to reinforce understanding.