0
0
Javaprogramming~10 mins

For loop syntax in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop syntax
Initialize i=0
Check: i < 3?
NoEXIT
Yes
Execute body
Update: i = i+1
Back to Check
The loop starts by setting i to 0, then checks if i is less than 3. If yes, it runs the loop body, then increases i by 1 and repeats. If no, it stops.
Execution Sample
Java
for (int i = 0; i < 3; i++) {
    System.out.println(i);
}
This code prints numbers 0, 1, and 2 using a for loop.
Execution Table
Iterationi valueCondition (i < 3)ActionOutput
10truePrint 0, i++0
21truePrint 1, i++1
32truePrint 2, i++2
43falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at iteration 4 (see execution_table row 4), so the loop exits.
When is the value of i increased?
i is increased after the loop body runs each time (see execution_table Action column), before the next condition check.
What values of i are printed?
Values 0, 1, and 2 are printed during iterations 1 to 3 (see Output column in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during iteration 2?
A0
B2
C1
D3
💡 Hint
Check the 'i value' column in execution_table row for iteration 2.
At which iteration does the loop condition become false?
AIteration 4
BIteration 3
CIteration 1
DNever
💡 Hint
Look at the 'Condition (i < 3)' column in execution_table.
If the loop condition changed to i <= 3, how many times would the loop run?
A3 times
B4 times
C2 times
D5 times
💡 Hint
Think about when i <= 3 is true for i values 0 to 4.
Concept Snapshot
For loop syntax in Java:
for (initialization; condition; update) {
    // code to repeat
}
- Initialization runs once at start.
- Condition checked before each loop; if false, loop ends.
- Update runs after each loop iteration.
- Loop body runs only if condition is true.
Full Transcript
This visual trace shows how a Java for loop works step-by-step. The loop starts by setting i to 0. Then it checks if i is less than 3. If yes, it runs the loop body which prints i, then increases i by 1. This repeats until i reaches 3, when the condition becomes false and the loop stops. The execution table tracks each iteration's i value, condition check, action, and output. The variable tracker shows how i changes from 0 to 3. Key moments clarify why the loop stops at i=3, when i increases, and which values print. The quiz tests understanding of i values, loop exit, and condition changes. The snapshot summarizes the for loop syntax and behavior in Java.