Sub topic 1
How loops repeat work
A loop repeats a set of instructions. It lets you do the same work without writing those instructions many times.
A condition is a test that is either true or false. A loop uses a condition to decide whether to repeat. The loop body is the group of instructions inside the loop. An iteration is one pass through that body.
Repeat while a condition is true
A while loop checks its condition before each iteration. If the condition is false at the start, the body never runs.
Save this program as Main.java:
public class Main {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}
}
}Compile and run it with:
javac Main.java
java MainThe program prints 0, 1, and 2, each on its own line.
Here, count < 3 means “count is less than 3.” The loop first checks that 0 < 3 is true, then prints 0. The statement count++ adds 1 to count. The loop checks the condition again and repeats.
After printing 2, the loop adds 1 to make count equal to 3. The condition is now false, so the loop stops.
Run once before testing with do-while
A do-while loop checks its condition after the body runs. This means the body runs at least once, even if the condition is false at the start.
Replace the contents of Main.java with this program, then compile and run it using the same commands:
public class Main {
public static void main(String[] args) {
int count = 3;
do {
System.out.println(count);
count++;
} while (count < 3);
}
}This program prints 3 once. It then increases count to 4 and checks 4 < 3. That condition is false, so the loop stops. Notice the semicolon after the condition.
Use while when the body may need to run zero times. Use do-while when it must run at least once.
Exercise
If the while example starts with count equal to 3, what does it print? What does the do-while example print?
Show answer
The while loop prints nothing because its condition is false at the start. The do-while loop prints 3 once because it checks the condition after its body runs.