Sub topic 2
Repeat while a condition is true
A loop repeats a section of code. A while loop repeats that code for as long as a test is true. It is useful when you want to keep working until something changes, such as a count reaching a limit or a total reaching a goal.
A condition is a test whose result is true or false. The code between the braces after while is the loop’s body. Each time the body runs is an iteration, or one pass through the loop.
A while loop checks its condition before each iteration. If the condition is false at the start, the body does not run at all.
Count with a while loop
This program prints three numbers. A counter is a variable used to track progress through a loop. Here, count is the counter.
Save the program as CountExample.java:
public class CountExample {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}
System.out.println("Done!");
}
}In a terminal, run:
javac CountExample.java
java CountExampleThe program prints 0, 1, 2, and Done!, each on its own line.
Here is what the loop does:
- It starts with
countset to0. - It tests
count < 3. The symbol<means “less than.” - If the condition is true, it prints
countand adds1to it. The statementcount++means “add one tocount.” - It returns to the condition and tests it again.
- When the condition is false, it skips the body and moves to the statement after the loop.
The final message is outside the braces, so it runs after the loop finishes.
Follow each test
A trace is a step-by-step record of what a program does. Use this table to follow the value of count through the loop.
| `count` at the test | Is `count < 3` true? | What happens next? |
|---|---|---|
| `0` | Yes | Print `0`, then change `count` to `1`. |
| `1` | Yes | Print `1`, then change `count` to `2`. |
| `2` | Yes | Print `2`, then change `count` to `3`. |
| `3` | No | Skip the body and print `Done!`. |
Notice that 3 is not printed by the loop. When count is 3, the condition count < 3 is false.
The condition is checked between iterations, not after every statement in the body. For example, in the last iteration, count++ changes count to 3. Any remaining statements inside the body would still run before the loop tests the condition again.
Start with a false condition
Try changing the first line inside main to set count to 3 instead of 0. Then compile and run the program again.
The first test, 3 < 3, is false. The loop body runs zero times, so the program prints only Done!.
This behavior matters when your program may already have reached its goal. A while loop does not make the program do the work once just because the loop is present.
Repeat until a total reaches a goal
A counter is not the only value a while condition can test. This program adds to a savings total until the total is at least the goal.
Save it as SavingsExample.java:
public class SavingsExample {
public static void main(String[] args) {
int total = 0;
int goal = 20;
while (total < goal) {
total = total + 7;
System.out.println("Saved: " + total);
}
System.out.println("Goal reached!");
}
}Run it with:
javac SavingsExample.java
java SavingsExampleIt prints Saved: 7, Saved: 14, Saved: 21, and then Goal reached!.
After the third addition, total is 21. The condition is tested again, and 21 < 20 is false. The loop stops. The total can go past the goal because each addition is 7; the condition asks only whether the total is still below the goal.
If you change goal to 0, the loop body does not run. The program prints only Goal reached!.
Make sure the condition can change
A while loop does not update its variables for you. In the counting example, count++ moves count toward 3. Without that statement, count would stay at 0, and count < 3 would stay true. The program would keep printing 0.
Before running a loop, ask: “What can make this condition false?” In the savings example, adding 7 changes total until it is no longer below goal.
Exercise
Exercise
If count starts at 3, what does this loop print? Why does it stop? while (count > 0) { System.out.println(count); count--; }
Show answer
It prints 3, 2, and 1, each on its own line. count-- subtracts one each time. When count reaches 0, count > 0 is false, so the body does not run again.