How to use for and while loops
Use a for loop
A for loop groups initialization, condition, and update. This example prints zero through four.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Use a while loop
A while loop tests before every iteration. Update the controlling value so the loop can finish.
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
Use do-while
A do-while loop tests after its body, so the body always runs at least once.
int choice = 1;
do {
System.out.println("Choice: " + choice);
choice++;
} while (choice <= 3);
Prevent endless loops
- Make the loop condition become false eventually.
- Check boundary operators such as
<versus<=. - Trace the loop variable by hand when output is unexpected.