Why loops: repetition without copy-paste
On This Lesson 11 topics
Lesson Overview
So far every statement in your programs ran once, from top to bottom, or was skipped by an if. Real tasks repeat: print every line of a receipt, check every attempt in a game, process every order in a batch. A loop is a statement that repeats a block of code while a condition holds.
We will use one picture for the whole module: running laps on a track. You start at lap 1, before each lap you check "have I finished?", and after each lap the lap counter goes up by one. Those three ideas, a starting point, a finish check, and a counter update, are the three parts of every loop.
Why this matters: backend programs spend most of their time doing the same thing to many items: many rows, many requests, many messages. Loops are how you write that thing once.
This lesson builds on BEG-012: you can already write a condition and use it in an if. A loop uses the same kind of condition, but asks it again and again.
Learning Objectives
By the end of this lesson you will be able to:
- Explain why copying a line many times is fragile.
- Define a loop and an iteration.
- Name the three parts of a loop: start, condition, update.
- Read a simple
forloop and say what it prints. - Name the three loop statements in Java:
for,while, anddo-while. - Say how the lap analogy maps to the code, and where it stops.
Written Explanation
The problem: repeating by hand
Suppose you need to print Lap 1 to Lap 5. You could write five System.out.println lines. That works, until:
- the count changes to 100 (you paste 95 more lines),
- the text changes (you edit every line, and miss one),
- the count is not known until the program runs (you cannot write the right number of lines at all).
Copy-paste code is slow to write, easy to get inconsistent, and impossible when the count is unknown. A loop fixes all three: write the line once and say how many times to repeat it.
What a loop is
A loop repeats a block of statements while a condition is true. One pass through the block is called an iteration. When the condition becomes false, the loop ends and the program continues with the next statement after it.
Here is the smallest useful loop:
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}Read it as: "Start with i equal to 1. While i is at most 5, run the body, then add 1 to i."
The three parts
Every loop needs three things, and each one matches the track picture:
| Part | In the code above | On the track |
|---|---|---|
| Start | int i = 1 | You begin at lap 1 |
| Condition | i <= 5 | Before each lap, "have I run five laps yet?" |
| Update | i++ | After each lap, the counter goes up |
The body is the code in braces: the running itself. If any part is wrong, the loop is wrong. A bad start gives the wrong first lap, a bad condition runs too many or too few laps, and a missing update means you never reach the finish line. The last two bugs get a whole lesson of their own (L06).
The order of events
The for statement in the Java Language Specification works in a fixed order: the start part runs once, then the condition is checked; if it is true the body runs, then the update runs, then the condition is checked again. When the condition is false the loop ends. So the condition is checked one more time than the body runs: in our example, six checks (i equal to 1 to 5, then 6) and five iterations.
Three loop statements
Java has three loop statements. They all repeat a block, and they differ in where the three parts are written and when the condition is checked:
| Statement | Best when | Condition checked |
|---|---|---|
for | You know how many times to repeat | Before each iteration |
while | You repeat until something happens | Before each iteration |
do-while | The body must run at least once | After each iteration |
This module teaches them one at a time. Today you only need to read a for loop and understand what a loop is.
Where the analogy stops
On a real track, you stop when you are tired. In a program, the loop stops only when its condition becomes false (or when you use break, which L04 covers). The computer will never decide "that is enough". If the condition stays true forever, the loop runs forever, and you must stop the program yourself.
Examples
Example 1: five laps (simple)
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}
System.out.println("Finished");Output:
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
FinishedFinished is outside the braces, so it runs once, after the loop ends. Change 5 to 100 and you get 100 laps with no other edit.
Example 2: a running total (practical)
A loop can carry information from one iteration to the next through a variable declared before it:
int total = 0;
for (int day = 1; day <= 3; day++) {
total += day * 10;
System.out.println("After day " + day + ": " + total);
}Output:
After day 1: 10
After day 2: 30
After day 3: 60total lives outside the loop, so it keeps its value between iterations: the box from Module BEG-009 remembers. day is created by the loop and, as L02 explains, exists only inside it.
Example 3: a batch of orders (realistic)
A shop applies the same price calculation to every order in a batch. Here the "orders" are numbered 1 to 4 and the price is 12.50 times the order number, a stand-in for real order data:
int orders = 4;
for (int n = 1; n <= orders; n++) {
double price = 12.50 * n;
System.out.println("Order " + n + " costs " + price);
}Output:
Order 1 costs 12.5
Order 2 costs 25.0
Order 3 costs 37.5
Order 4 costs 50.0The count is stored in a variable, orders. When the shop has 400 orders, only that one number changes. This is the pattern behind most backend loops: one block of logic, applied to every item.
Backend Insight
A server handling a busy day does the same few steps for thousands of items: read a record, check it, add it to a result. That is a loop. Two consequences matter early:
- The loop body is multiplied. A step that takes a tiny amount of time becomes significant when it runs a million times. Later in the course (BEG-039) you will measure how the work grows as the data grows; "how many times does the body run?" is the first question, and you will practise answering it in L05.
- A loop that never ends is an outage. A service stuck in an endless loop stops answering requests. Always know why your loop will end: before you run a loop, say in one sentence which change to which variable will make its condition false.
Common Mistakes
Mistake 1: Copy-pasting instead of looping
- Incorrect: ten nearly identical
printlnlines. - Correct: one
printlninside a loop that runs ten times.
If you notice yourself pasting a line and changing one number, you are looking at a loop.
Mistake 2: Putting the "once" statement inside the loop
for (int i = 1; i <= 3; i++) {
System.out.println("Starting the race"); // prints 3 times
System.out.println("Lap " + i);
}Anything in the braces runs every iteration. A statement that should run once belongs before or after the loop.
Mistake 3: Declaring the running total inside the loop
If int total = 0; sits inside the braces, a new total is created each iteration and the old one is lost. Declare it before the loop.
Mistake 4: Forgetting the braces for a multi-line body
Without braces a for repeats only the next single statement. Use braces always, even for one line; it avoids a whole class of errors.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. Name the three parts of a loop and say what each does.
Show solution A1
A1. Start: sets the first value of the counter, once. Condition: checked before each iteration to decide whether to continue. Update: changes the counter after each iteration.
A2. What does this print?
for (int i = 1; i <= 3; i++) {
System.out.println("Hi " + i);
}Show solution A2
A2.
Hi 1
Hi 2
Hi 3A3. Name the three loop statements in Java and which of them is best when the count is known.
Show solution A3
A3. for, while, and do-while. for is the usual choice when the count is known.
Level B: Application
B1. Write a loop that prints Step 1 to Step 8, then Done once.
Show solution B1
B1.
for (int i = 1; i <= 8; i++) {
System.out.println("Step " + i);
}
System.out.println("Done");B2. The loop below should print the numbers 1 to 4 and their running total, but prints 1 1, 2 2, 3 3, 4 4. Find and fix the bug.
for (int i = 1; i <= 4; i++) {
int total = 0;
total += i;
System.out.println(i + " " + total);
}Show solution B2
B2. total is declared inside the loop, so it resets to 0 every iteration. Move int total = 0; above the loop. The output becomes 1 1, 2 3, 3 6, 4 10.
B3. How many times does the body of for (int i = 1; i <= 6; i++) run? How many times is the condition checked?
Show solution B3
B3. The body runs 6 times (i is 1 to 6). The condition is checked 7 times: six true checks and a final false check when i is 7.
Level C: Challenge
C1. Write a loop that prints the first five multiples of 3 (3, 6, 9, 12, 15) using the loop variable in a calculation, not a list of numbers.
Show solution C1
C1.
for (int i = 1; i <= 5; i++) {
System.out.println(i * 3);
}C2. Explain in two sentences why a loop is better than copy-paste when a program must repeat something a number of times it only learns at run time.
Show solution C2
C2. With copy-paste you would have to write the number of lines before the program runs, but the count is only known later, so it cannot be done. A loop takes the count from a variable, so one block of code works for any count.
Mini Challenge
Write a program that prints a short "training plan". It must:
- Store the number of days (for example 7) in an
intvariable. - Use a loop that prints
Day 1: run,Day 2: run, and so on up to that number. - After the loop print
Plan completeonce. - Keep a running total of kilometres: add 2 each day and print the total after the loop.
Check your work: change the number of days to 3, and then to 10. Only that one variable should need to change, and the total should be twice the number of days.
Summary & Next Lesson
Key takeaways
- A loop repeats a block while a condition is true; each pass is an iteration.
- Every loop has a start, a condition, and an update.
- In a
forloop the start runs once; the condition is checked before every iteration; the update runs after every iteration. - Java has
for,while, anddo-while. - A variable that must survive between iterations is declared before the loop.
Next lesson
The next lesson, "The for loop", looks at the for statement in detail: counting up and down, changing the step, and tracing a loop by hand.
Self-check
- What is one pass through a loop body called?
- Name the three parts of a loop.
- Why is a copy-pasted block worse than a loop?
- In
for (int i = 1; i <= 5; i++), when doesi++run? - Where should you declare a running total used inside a loop?
Show answers
- An iteration.
- Start, condition, and update.
- It is slow to write, inconsistent when edited, and impossible if the count is unknown until run time.
- After each execution of the body, before the next condition check.
- Before the loop, so it keeps its value from one iteration to the next.
References
- Oracle, The for Statement (Java Tutorials). It describes the initialization, termination, and increment expressions, and that the variable declared in the initialization is scoped to the loop.
- Oracle, The while and do-while Statements. It supports the statement that
whilechecks at the top anddo-whileat the bottom of the loop. - Oracle, Java Language Specification, SE 21, Chapter 14: Blocks, Statements, and Patterns. It defines the order in which a basic
forstatement runs its parts. The lap analogy is this course's own teaching addition. The code examples were compiled and run with JDK 21.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.