Iteration (Loops)
B2.3.3 - Construct programs that utilize looping structures to perform repeated actions.
Key Concepts
Iteration allows a block of code to repeat without writing it multiple times. Java has three loop types - choosing the right one depends on the situation. (Python has two: while and for. There is no do-while in Python - Example 2 shows how to get the same effect.)
| Loop type | Condition check | Best used when |
|---|---|---|
while | Before each iteration | You repeat while a condition is true; may not run at all |
do-while | After each iteration | The body must execute at least once |
for | Before each iteration | You know exactly how many times to repeat |
A pre-condition loop (
while,for) checks the condition before running the body - so it may execute zero times. A post-condition loop (do-while) checks after - guaranteeing at least one execution. Whichever loop you use, something in the body must move toward making the condition false, or you have written an infinite loop.
Worked Examples
Example 1: while Loop - Countdown
The while loop checks the condition before each iteration. If the condition is false from the start, the body never runs.
int count = 5;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Go!");
count = 5
while count > 0:
print(count)
count = count - 1
print("Go!")
Output:
5
4
3
2
1
Go!
How it works:
countstarts at 5. The conditioncount > 0is true, so the body runs.- Each iteration prints
countand then decrements it. - When
countreaches 0, the condition is false and the loop ends.
Example 2: do-while Loop - Input Validation
The do-while loop runs the body first, then checks the condition. This guarantees at least one execution - ideal for menus and input validation.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a number between 1 and 10: ");
number = input.nextInt();
} while (number < 1 || number > 10);
System.out.println("You entered: " + number);
# Python has no do-while loop.
# The IB pattern: read once BEFORE the loop (priming read),
# then repeat while the value is invalid.
number = int(input("Enter a number between 1 and 10: "))
while number < 1 or number > 10:
number = int(input("Enter a number between 1 and 10: "))
print("You entered:", number)
How it works:
- The prompt runs at least once - the user must enter something before we can check it.
- If
numberis outside 1-10, the condition is true and the loop repeats. - Once valid input is entered, the condition is false and the loop ends.
The
do-whilepattern is the natural choice for “ask, then validate” scenarios. Awhileloop would require duplicating the prompt before and inside the loop.
Example 3: for Loop - Multiplication Table
The for loop combines initialisation, condition, and update in one line - perfect when the number of iterations is known.
int tableNum = 7;
System.out.println("Multiplication table for " + tableNum + ":");
for (int i = 1; i <= 12; i++) {
System.out.println(tableNum + " x " + i + " = " + (tableNum * i));
}
table_num = 7
print("Multiplication table for " + str(table_num) + ":")
for i in range(1, 13): # range(1, 13) gives i = 1 to 12 - the stop value is not included
print(table_num, "x", i, "=", table_num * i)
Output:
Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 12 = 84
Structure: for (initialise; condition; update)
- Initialise:
int i = 1- runs once before the loop starts - Condition:
i <= 12- checked before each iteration; loop stops when false - Update:
i++- runs after each iteration
Example 4: Accumulator Pattern - Running Total
A common loop pattern: use a variable to accumulate a result across iterations.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int total = 0;
int count = 0;
System.out.println("Enter numbers to sum (enter -1 to stop):");
int num = input.nextInt();
while (num != -1) {
total += num;
count++;
num = input.nextInt();
}
System.out.println("Sum: " + total);
System.out.println("Numbers entered: " + count);
if (count > 0) {
System.out.println("Average: " + (double) total / count);
}
total = 0
count = 0
print("Enter numbers to sum (enter -1 to stop):")
num = int(input())
while num != -1:
total = total + num
count = count + 1
num = int(input())
print("Sum:", total)
print("Numbers entered:", count)
if count > 0:
print("Average:", total / count) # / always gives a decimal in Python - no cast needed
Key patterns:
- Accumulator:
total += num- builds up a running sum - Counter:
count++- tracks how many values were processed - Sentinel value:
-1signals “stop” - the loop runs until the sentinel is entered
The sentinel value (
-1here) is not included in the total. Always read the first value before the loop, then read subsequent values at the end of the loop body.
Example 5: Nested Loops - Star Pattern
Loops can be placed inside other loops. The inner loop completes fully for each iteration of the outer loop.
int rows = 5;
for (int row = 1; row <= rows; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("* ");
}
System.out.println();
}
rows = 5
for row in range(1, rows + 1):
for col in range(1, row + 1):
print("* ", end="") # end="" keeps printing on the same line
print() # move to the next line
Output:
*
* *
* * *
* * * *
* * * * *
How it works:
- The outer loop controls which row we are on (1 to 5).
- The inner loop prints stars - the number of stars equals the current row number.
System.out.println()after the inner loop moves to the next line.
When tracing nested loops, track both loop variables separately. The inner loop variable resets to its start value for every iteration of the outer loop.
Example 6: Savings Goal - Combining Patterns
A student is saving up for something that costs 120. They pay in 10 in the first week and 5 more each week after that, and they stop after 8 weeks even if the goal has not been met. The loop has two reasons to stop: the goal is reached, or the weeks run out. It combines a counter, a running total, a boolean flag and a while loop with two exit conditions.
int goal = 120; // amount to save
int maxWeeks = 8; // stop after 8 weeks even if the goal is not met
int week = 0;
int saved = 0;
boolean reached = false;
while (!reached && week < maxWeeks) {
week++;
int deposit = 10 + 5 * (week - 1); // 10 in week 1, then 5 more each week
saved += deposit;
System.out.println("Week " + week + ": paid in " + deposit + ", total " + saved);
if (saved >= goal) {
reached = true;
}
}
if (reached) {
System.out.println("Goal reached in week " + week + ".");
} else {
System.out.println("Goal not reached after " + maxWeeks + " weeks. Total saved: " + saved + ".");
}
goal = 120 # amount to save
max_weeks = 8 # stop after 8 weeks even if the goal is not met
week = 0
saved = 0
reached = False
while reached == False and week < max_weeks:
week = week + 1
deposit = 10 + 5 * (week - 1) # 10 in week 1, then 5 more each week
saved = saved + deposit
print("Week " + str(week) + ": paid in " + str(deposit) + ", total " + str(saved))
if saved >= goal:
reached = True
if reached == True:
print("Goal reached in week " + str(week) + ".")
else:
print("Goal not reached after " + str(max_weeks) + " weeks. Total saved: " + str(saved) + ".")
Output:
Week 1: paid in 10, total 10
Week 2: paid in 15, total 25
Week 3: paid in 20, total 45
Week 4: paid in 25, total 70
Week 5: paid in 30, total 100
Week 6: paid in 35, total 135
Goal reached in week 6.
Key patterns:
- Flag variable:
reachedrecords whether the goal has been met, and the loop condition checks it before every pass - Compound condition:
!reached && week < maxWeeksgives the loop two reasons to stop - Counter:
weeklimits the number of passes, and the deposit is worked out from it - Accumulator:
savedkeeps the running total, as in Example 4
Change goal to 250 and run it again. The loop now runs all 8 weeks, the total reaches 220, and the else branch prints Goal not reached after 8 weeks. Total saved: 220.
Quick Check
Q1. Which loop is guaranteed to execute its body at least once?
Q2. How many times does the body of for (int i = 0; i < 5; i++) { System.out.println(i); } execute?
Q3. What happens if a while loop's condition is false when first evaluated?
Q4. In for (int i = 0; i < 10; i++), when does i++ execute?
Q5. What does this code do?int count = 5; while (count > 0) { System.out.println(count); }
Q6. How many times does the inner body execute?for (int row = 1; row <= 3; row++) { for (int col = 1; col <= row; col++) { System.out.print("*"); } }
Trace Exercise
Trace this loop - fill in the values of i and product after each iteration.
int product = 1;
int n = 4;
for (int i = 1; i <= n; i++) {
product = product * i;
}
product = 1
n = 4
for i in range(1, n + 1):
product = product * i
| Iteration | i (at start of body) | product after body |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
What is product after the loop ends?
What does this program compute?
Trace Exercise 2 - Nested Loop
Trace the nested loop - fill in the output produced at each step.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(i + "," + j);
}
}
for i in range(1, 4):
for j in range(1, 3):
print(str(i) + "," + str(j))
| Step | i | j | Output |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 |
How many total lines of output?
Code Completion
This program uses a while loop with a step value of 2 to print all even numbers from 2 to 20. Complete the missing parts to set the correct start value, end condition, and increment.
int num = ;
while (num <= ) {
System.out.println(num);
num += ;
} This program uses the accumulator pattern inside a for loop to calculate the sum of all integers from 1 to n. Complete the missing parts to initialise the accumulator, set the loop start value, and perform the running total update.
int n = 100;
int total = ;
for (int i = ; i <= n; i++) {
total ;
}
System.out.println("Sum: " + total); Spot the Error
This code is supposed to print the numbers 1 to 5 using a while loop, but it does not stop after 5: it keeps printing numbers. Select the buggy line, then choose the correct fix.
int i = 1;
while (i <= 5) {
System.out.println(i);
i--;
}What is wrong and how do you fix it?
This code is supposed to calculate the sum of integers from 1 to 10 using a for loop, but the loop condition has an off-by-one error that causes it to miss one value. The correct answer is 55 but this code prints 45. Find the bug.
int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i;
}
System.out.println("Sum of 1 to 10: " + sum);What is wrong and how do you fix it?
Predict the Output
This code demonstrates a while loop that counts down from 10 using a non-standard step value of 3. Pay attention to which values of x satisfy the loop condition and when the loop stops.
What does this code print? Type the exact output.
int x = 10;
while (x > 0) {
System.out.print(x + " ");
x -= 3;
}
x = 10
while x > 0:
print(x, end=" ")
x = x - 3
This code uses nested for loops to print a decreasing-width number pattern. The inner loop’s start value depends on the outer loop variable, so each row begins at a different number. Trace both loop variables carefully.
What does this code print?
for (int i = 1; i <= 4; i++) {
for (int j = i; j <= 4; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for i in range(1, 5):
for j in range(i, 5):
print(j, end=" ")
print()
1 2 3 4
2 3 4
3 4
4Practice Exercises
Core
-
Countdown timer - Write a program that asks the user for a starting number and prints a countdown to 1, then prints “Go!”. Use a
whileloop. -
Sum of range - Use a
forloop to calculate and print the sum of all integers from 1 to 100. -
Even number printer - Use a
forloop to print all even numbers from 2 to 50, separated by spaces. -
Input validation - Use a
do-whileloop to ask the user for a test score (0-100). Keep asking until they enter a valid value, then print the score. (Python: use a priming read +whileloop, as in Example 2.)
Extension
-
FizzBuzz - Print numbers from 1 to 30. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz”. For multiples of both, print “FizzBuzz”.
-
Right triangle - Use nested loops to print a right triangle of
*characters with a height entered by the user:* * * * * * * * * * -
Average calculator - Read numbers from the user until they enter
-1(sentinel). Print the count, sum, and average. Handle the case where no numbers are entered.
Challenge
- Number pyramid - Use nested loops to print a centred number pyramid:
1 2 3 4 5 6 7 8 9 10 - Simple menu system - Create a calculator with a
do-whilemenu loop (Python: priming read +while). Options: (1) Add, (2) Subtract, (3) Multiply, (4) Quit. After each operation, return to the menu until the user quits.
GitHub Classroom
A class assignment on GitHub Classroom: use it when your teacher has set it. It needs a free GitHub account.
Working in the Codespace
- Accept and open. Accept the assignment above, open the link in the email from GitHub, then press Open in Codespace. In Java, change the status bar from Lightweight to Standard mode.
- Write and check. Open
src/Iteration.javaand complete eachTODO. Press Run and compare the output with the comments, or runbash run-tests.shin the Terminal. - Submit. In Source Control, write a message, press Commit, then Sync Changes. Your teacher’s feedback arrives as a pull request called Feedback.
Connections
Prerequisites:
- Selection (if/else) - conditions used in loop headers
- Variables & Data Types - declaring and updating loop variables
Related Topics:
- 1D Arrays - loops are essential for array traversal
- 2D Arrays - nested loops traverse rows and columns
Where this leads:
- 1D Arrays - store many values and work through them with a loop
- Algorithms - loops power searching and sorting
Once you are comfortable with loops, 1D arrays become natural - nearly every array operation uses a loop to traverse, search, or modify elements.