Sub topic 1
How loops repeat work
A loop lets a program repeat a group of instructions. Instead of writing the same instructions again and again, you write them once and let the loop run them.
Loops are useful when a program needs to count, add several values, or repeat a task until something changes. For example, a program might print a reminder three times. It can use a loop to print the message once per repetition.
An iteration is one pass through a loop’s instructions. A loop that prints a message three times has three iterations.
A loop often uses a condition, which is a test that produces either true or false. The result helps the program decide whether to repeat. A condition might ask, “Is the count less than 3?”
A loop also has a body. The body is the group of instructions that runs on each iteration. The body can do more than one thing, such as print a value and then change it.
A first loop
Here is a complete Java program that counts from 0 to 2. It then prints Done.
public class Main {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count = count + 1;
}
System.out.println("Done");
}
}To run it, save the code in a file named Main.java. You need a Java Development Kit, or JDK, installed. A JDK is a set of tools for building and running Java programs.
Open a terminal in the folder that contains the file and run:
javac Main.java
java MainThe first command prepares the Java file to run. The second command runs the program. You should see:
Count: 0
Count: 1
Count: 2
DoneJava starts this program at main and follows its instructions. The loop causes two of those instructions to run more than once.
This example uses the word while to start the loop. For now, focus on the parts shared by many loops: a starting value, a condition, a body, and a change that affects a later check.
Find the starting value
This line runs before the loop begins:
int count = 0;A variable is a named place for a value. Here, the variable is named count. The word int tells Java that count holds a whole number. Its starting value is 0.
The starting value matters because the loop uses count in its condition. Java checks the condition using the value that count has at that moment.
Find the condition
The condition in the example is:
count < 3The symbol < means “less than.” The condition asks whether the current value of count is less than 3.
An expression is code that Java works out to get a value. This condition is an expression whose value is either true or false. These two values are called Boolean values.
At the start, count is 0. Since 0 is less than 3, the condition is true. The program runs the loop body.
Find the body
The loop body is between the braces, { and }, after the condition:
System.out.println("Count: " + count);
count = count + 1;These two lines run in order during each iteration.
The first line prints Count: followed by the current value of count. The second line changes count.
In count = count + 1, Java works out the value on the right side first. It adds 1 to the current value of count, then stores the result back in count. For example, if count is 0, the line changes it to 1.
After the body finishes, this loop checks its condition again. The check uses the new value of count.
The final System.out.println("Done"); line is outside the loop body. It runs after the loop ends, not once per iteration.
Follow the loop step by step
To trace a program is to follow its instructions in order and record what happens. Tracing is useful because a loop can run the same lines with different values each time.
The table shows each condition check in the example.
| Check | Value of `count` | Is `count < 3` true? | What happens next? |
|---|---|---|---|
| 1 | 0 | Yes | Print `Count: 0`, then change `count` to 1 |
| 2 | 1 | Yes | Print `Count: 1`, then change `count` to 2 |
| 3 | 2 | Yes | Print `Count: 2`, then change `count` to 3 |
| 4 | 3 | No | Leave the loop |
There are three iterations but four condition checks. The last check is needed to discover that the condition is false.
After the fourth check, the program continues with the line after the loop and prints Done.
Notice that the arrow goes back to the condition, not to the line that sets count to 0. The starting line runs once. If it ran again on every pass, count would keep returning to 0.
The diagram describes this example. Not every kind of loop checks its condition at the same point. For this loop, the check happens before each iteration.
Exercise
In the counting program, what is the value of count when the loop ends?
Show answer
It is 3. The third iteration changes count from 2 to 3, and the next condition check is false.
A condition is checked again
The words count < 3 do not keep a single answer for the whole program. Each time Java reaches the check, it works out the expression using the current value of count.
That is why the same condition can be true at one moment and false later:
- When
countis1,count < 3istrue. - When
countis3,count < 3isfalse.
The condition does not change its wording. The value used by the condition changes.
In the counting program, the body changes that value with count = count + 1. This change moves the program toward a point where the condition is false. Once the condition is false, this loop stops repeating its body.
A condition can also be false on the very first check. In that case, this loop runs its body zero times.
Try changing the starting line in the program to:
int count = 3;Keep the rest of the program the same. On the first check, count < 3 is false. The program does not print any Count: lines. It skips the body and prints only:
DoneThis does not mean the whole program stopped. Only the loop body was skipped. The instruction after the loop still ran.
The order inside the body matters
Each iteration follows the body’s instructions from top to bottom. In the first program, printing happens before the addition:
- Print the current value of
count. - Add
1tocount. - Check the condition again.
That order is why the first printed value is 0. The addition has not happened yet when the first print runs.
Imagine moving the print line after the addition. The first iteration would change count from 0 to 1 and then print 1. With the same starting value and condition, the printed count values would be 1, 2, and 3.
The last value may seem surprising. On the third pass, the condition is checked while count is 2, so the body begins. The addition changes count to 3, but the rest of that body still runs. Only after the body finishes does this loop check the condition again.
This gives you a useful tracing habit: do not stop in the middle of the body just because a value has changed. Follow the remaining instructions, then go to the next check.
Exercise
If the counting program prints count after adding 1 instead of before, which count values does it print?
Show answer
It prints 1, 2, and 3. Each pass adds first and then prints; the condition is checked again after the body finishes.
Use repeated work to build a result
A loop can do more than display a count. It can use each pass to build a result. The next program adds the numbers 1, 2, and 3.
Save this version as Main.java and run it in the same way as the first program.
public class Main {
public static void main(String[] args) {
int total = 0;
int next = 1;
while (next <= 3) {
total = total + next;
next = next + 1;
}
System.out.println("Total: " + total);
}
}The output is:
Total: 6This program has two variables with different jobs:
nextholds the number to add on the current pass.totalholds the sum built so far.
The condition is next <= 3. The symbol <= means “less than or equal to.” So the condition is true when next is 1, 2, or 3.
On each pass, the body first adds next to total. It then adds 1 to next. Here is the trace:
| Pass | `next` at the start | Addition | `total` after addition | `next` after its change |
|---|---|---|---|---|
| 1 | 1 | `0 + 1` | 1 | 2 |
| 2 | 2 | `1 + 2` | 3 | 3 |
| 3 | 3 | `3 + 3` | 6 | 4 |
After pass 3, the condition is checked with next equal to 4. The result is false, so the loop ends. The print line is outside the loop, so it prints the finished total once.
The values in the table show why the order of the two body lines matters. The program adds the current next value before it changes that value. On the first pass, it adds 1, not 2.
The two variables also show that a loop can carry information from one pass to the next. When the first pass ends, total is 1. The second pass starts with that value; it does not start total over at 0.
Ask four questions when reading a loop
When you meet a loop, you can understand its work by answering four questions:
- What values does it start with? In the adding program,
totalstarts at0andnextstarts at1. - When is the condition checked? In these examples, it is checked before each pass through the body.
- What does the body do, in order? In the adding program, it adds
nexttototal, then changesnext. - What happens after the loop? In the adding program, the finished total is printed.
Write down the values after each pass if the answer is not clear. You do not have to work out every pass in your head. Even a small table can show which values change and which instructions repeat.
The key idea is that a loop combines repeated instructions with changing values. The body can be the same on every pass, but the result of that body can be different because the values it uses are different.
Exercise
In the adding program, what is total after the first two passes? What is next at that point?
Show answer
total is 3, because the program has added 1 and 2. next is 3, ready for the next condition check.
Exercise
Suppose the adding program starts with next equal to 4 instead of 1. What does it print?
Show answer
It prints Total: 0. The first check of next <= 3 is false, so the body does not run and total stays at its starting value.