0
0
Javaprogramming~10 mins

Counter-based while loop in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Counter-based while loop
Initialize counter = 0
Check: counter < limit?
NoEXIT
Yes
Execute loop body
Update counter = counter + 1
Back to Check
Start with a counter, check if it is less than a limit, run the loop body if yes, then increase the counter and repeat until the condition is false.
Execution Sample
Java
int counter = 0;
while (counter < 3) {
    System.out.println(counter);
    counter++;
}
Print numbers 0, 1, 2 by increasing counter until it reaches 3.
Execution Table
StepcounterCondition (counter < 3)ActionOutput
10truePrint 0, counter++0
21truePrint 1, counter++1
32truePrint 2, counter++2
43falseExit loop
💡 counter reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
counter01233
Key Moments - 2 Insights
Why does the loop stop when counter equals 3?
Because the condition counter < 3 becomes false at step 4, so the loop exits as shown in the execution_table row 4.
When is the counter variable increased?
The counter is increased after printing the current value inside the loop body, as seen in the Action column of the execution_table rows 1 to 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of counter at step 2?
A2
B0
C1
D3
💡 Hint
Check the 'counter' column in execution_table row 2.
At which step does the loop condition become false?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table row 4.
If we change the limit from 3 to 5, how many times will the loop run?
A3 times
B5 times
C4 times
D6 times
💡 Hint
The loop runs while counter < limit, so it runs limit times starting from 0.
Concept Snapshot
Counter-based while loop syntax:
int counter = 0;
while (counter < limit) {
    // loop body
    counter++;
}
Loop runs while condition is true, counter updates each iteration.
Full Transcript
This example shows a counter-based while loop in Java. We start with counter at 0. Each time the loop checks if counter is less than 3. If yes, it prints the counter and then increases it by 1. When counter reaches 3, the condition becomes false and the loop stops. The execution table tracks each step, showing counter values, condition results, actions, and outputs. The variable tracker shows how counter changes after each iteration. Key moments clarify why the loop stops and when the counter increases. The quiz tests understanding of counter values, loop exit step, and effect of changing the limit.