← Back to Week 2 Hub

Loop Types: while vs do/while vs for

Three ways to repeat code in Java -- see them execute side by side

5
Ready -- press Step or Play
while loop
int i = 1, sum = 0;
while (i <= N) {
  sum += i;
  i++;
}
i
1
sum
0
Waiting...
int i = 1, sum = 0
i <= N ?
sum += i
i++
↩ back to condition
Done
do/while loop
int i = 1, sum = 0;
do {
  sum += i;
  i++;
} while (i <= N);
i
1
sum
0
Waiting...
int i = 1, sum = 0
sum += i
i++
i <= N ?
↩ back to body
Done
for loop
for (int i = 1; i <= N; i++) {
  sum += i;
}
// sum declared before loop
int sum = 0;
i
1
sum
0
Waiting...
int i = 1, sum = 0
i <= N ?
sum += i
i++
↩ back to condition
Done
Key Differences
Feature while do/while for
Checks condition Before body After body Before body
Minimum runs 0 1 0
Best for Unknown iterations At least once Known count

What if the condition is false from the start? (N = 0)

Set the slider to 0 and step through to see the difference, or press the button below for a quick demo.

Tip: Use for when you know how many times to loop. Use while when you're waiting for a condition. Use do/while when you need at least one iteration (rare in practice).

Color key: initialization | condition | body | update

← Object Lifecycle break vs continue →