Teacher Guide: Iteration (Loops)
Student page: Iteration IB Syllabus: B2.3.3 Estimated periods: 2–3 (90 min each) Prerequisites: Variables & Data Types, Selection
Contents
Lesson Plans
Period 1: for and while loops
| Phase | Time | Activity | Student Page Section |
|---|---|---|---|
| Warm-up | 10 min | “Print 1 to 100 without a loop” — absurdity motivates loops | — |
| Teach | 25 min | for loop anatomy (init, condition, update), while loop, loop choice guide | Key Concepts |
| Practice | 40 min | Core #1-3 (Countdown, Sum of range, Even numbers) | Practice Exercises |
| Wrap-up | 15 min | Quick Code Check MCQs | Quick Code Check |
Teaching notes:
- Three questions that map to for loop: “What repeats? What changes? What stays the same?”
- Loop choice guide: for = known count, while = condition-based (may run 0 times), do-while = must run once
- Infinite loop deliberately: let students write one in controlled environment, then ask “What was missing?”
Additional activities:
- Scanner deep-dive:
hasNextInt(), buffer/token/delimiter,nextInt()/nextLine()skip bug - Guessing game with extensions (attempt counter, difficulty levels, limited attempts)
Period 2: do-while, nested loops, sentinel patterns
| Phase | Time | Activity | Student Page Section |
|---|---|---|---|
| Warm-up | 10 min | “A menu must display before the user makes a choice — which loop?” | — |
| Teach | 20 min | do-while for input validation/menus, nested loops, sentinel value pattern | Worked Examples |
| Practice | 45 min | Core #4, Extension #5-7 | Practice Exercises |
| Wrap-up | 15 min | Trace exercise from student page | Trace Exercise |
Additional activities:
- Grade statistics program (max/min/average with sentinel value)
- Pair exchange: students swap solutions, give feedback on optimization
Period 3 (optional): Pattern programming and challenges
| Phase | Time | Activity | Student Page Section |
|---|---|---|---|
| Warm-up | 10 min | Draw a triangle of stars on paper — describe the pattern in words | — |
| Teach | 15 min | Pattern analysis: rows vs columns, relationship between outer/inner loop | — |
| Practice | 50 min | Extension #6 (right triangle), Challenge #8-9 (pyramid, menu) | Practice Exercises |
| Wrap-up | 15 min | Pattern programming showcase — students present solutions | — |
Additional pattern programming activities:
- Triangle of stars, chessboard (modulus), diagonal, cross, hollow square, number pyramid
- Each pattern reinforces the relationship between outer and inner loop variables
Differentiation
Supporting weaker students:
| Strategy | When to use | Example |
|---|---|---|
| Loop anatomy diagram | Can’t remember for loop parts | Label: for (init; condition; update) with arrows |
| While loop template | Confuses while and for | Provide skeleton: int i = 0; while (i < ???) { ... i++; } |
| Trace first, code second | Can’t write loop from scratch | Fill in trace table for sum 1-10, then translate to code |
| Reduce iteration count | Overwhelmed by debugging | “Print 1 to 5” before “1 to 100” — same logic, easier to verify |
Extending stronger students:
| Strategy | When to use | Example |
|---|---|---|
| Pattern programming | Finishes Core early | Chessboard (modulus), cross, hollow square |
| Guessing game | After Core #1 | Random number guessing game with attempt counter |
| Challenge exercises | Extended learners | #8 Number pyramid, #9 Menu system |
| Big O preview | After nested loops | “How many times does the inner print run for n rows?” → n² |
| Fibonacci sequence | After sentinel pattern | Generate first n Fibonacci numbers using a loop |
Answer Keys
Core 1: Countdown timer
import java.util.Scanner;
public class Countdown {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Start from: ");
int n = scanner.nextInt();
while (n >= 1) {
System.out.print(n + " ");
n--;
}
System.out.println("Go!");
scanner.close();
}
}
Expected output (input 5): 5 4 3 2 1 Go!
Common mistakes:
- Using
n > 0(works butn >= 1is clearer) - Forgetting to decrement n (infinite loop)
- Printing “Go!” inside the loop
Marking notes: Accept for loop version. Key: must count DOWN, must print “Go!” after loop ends.
Core 2: Sum of range
public class SumOfRange {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
Expected output: Sum: 5050
Common mistakes:
- Starting i at 0 instead of 1
- Using
< 100instead of<= 100 - Not initializing sum to 0
Marking notes: Gauss formula 100*101/2 is mathematically correct but misses the point (using a loop).
Core 3: Even number printer
public class EvenPrinter {
public static void main(String[] args) {
for (int i = 2; i <= 50; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
Expected output: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
Common mistakes:
- Using
i++and checkingi % 2 == 0inside (works but less efficient) - Starting at 0
Marking notes: Accept both approaches (start at 2 step 2, or start at 1 step 1 with if). Both are correct.
Core 4: Input validation
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int score;
do {
System.out.print("Enter a score (0-100): ");
score = scanner.nextInt();
if (score < 0 || score > 100) {
System.out.println("Invalid. Must be 0-100.");
}
} while (score < 0 || score > 100);
System.out.println("Valid score: " + score);
scanner.close();
}
}
Common mistakes:
- Using while instead of do-while (doesn’t prompt before first check)
-
Wrong condition logic (using && instead of )
Marking notes: MUST use do-while as specified. The condition score < 0 || score > 100 means “keep looping while invalid.”
Extension 5: FizzBuzz
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 30; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}
Common mistakes:
- Checking % 3 and % 5 separately BEFORE the combined check — prints “Fizz” for 15 instead of “FizzBuzz”. Order matters: combined check MUST come first.
Marking notes: The order of conditions is the key teaching point. Accept i % 15 == 0 as equivalent to i % 3 == 0 && i % 5 == 0.
Extension 6: Right triangle
import java.util.Scanner;
public class RightTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter height: ");
int height = scanner.nextInt();
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
scanner.close();
}
}
Expected output (height 4):
*
* *
* * *
* * * *
Common mistakes:
- Inner loop condition wrong (using
j <= heightinstead ofj <= i) - Forgetting println() after inner loop
Marking notes: Key insight: inner loop runs i times, not height times. The connection between outer and inner loop variable IS the pattern.
Extension 7: Average calculator (sentinel)
import java.util.Scanner;
public class AverageCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
System.out.print("Enter a number (-1 to stop): ");
int num = scanner.nextInt();
while (num != -1) {
sum += num;
count++;
System.out.print("Enter a number (-1 to stop): ");
num = scanner.nextInt();
}
if (count > 0) {
double avg = (double) sum / count;
System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
} else {
System.out.println("No numbers entered.");
}
scanner.close();
}
}
Common mistakes:
- Including -1 in the sum/count
- Division by zero when no numbers entered
- Integer division for average
Marking notes: MUST handle the edge case of no numbers entered (count == 0). Must NOT include sentinel in calculations. Must use double division for average.
Challenge 8: Number pyramid
import java.util.Scanner;
public class NumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
int num = 1;
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int s = 1; s <= rows - i; s++) {
System.out.print(" ");
}
// Print numbers for this row
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
scanner.close();
}
}
Expected output (4 rows):
1
2 3
4 5 6
7 8 9 10
Common mistakes:
- Resetting num each row
- Wrong number of leading spaces
- Not incrementing num correctly
Marking notes: Three nested patterns: spaces, numbers, newline. The counter num is NOT reset per row — it carries across rows. This is the key insight.
Challenge 9: Simple menu system
import java.util.Scanner;
public class MenuCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Calculator Menu ---");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Quit");
System.out.print("Choice: ");
choice = scanner.nextInt();
if (choice >= 1 && choice <= 3) {
System.out.print("Enter first number: ");
double a = scanner.nextDouble();
System.out.print("Enter second number: ");
double b = scanner.nextDouble();
if (choice == 1) {
System.out.println("Result: " + (a + b));
} else if (choice == 2) {
System.out.println("Result: " + (a - b));
} else {
System.out.println("Result: " + (a * b));
}
} else if (choice != 4) {
System.out.println("Invalid choice.");
}
} while (choice != 4);
System.out.println("Goodbye!");
scanner.close();
}
}
Common mistakes:
- Using while instead of do-while (menu must show before first choice)
- Not handling invalid choices
- Forgetting the quit condition
Marking notes: MUST use do-while. Must loop back to menu after each operation. Must handle invalid choice gracefully. Accept switch-case alternative.
Integration Notes
| Item | In Class | Homework | Link |
|---|---|---|---|
| Worked Examples | Walk through together | — | Worked Examples |
| Quick Code Check | End of Period 1 | — | Quick Code Check |
| Core #1-3 | Period 1 practice | — | Practice Exercises |
| Core #4, Extension #5-7 | Period 2 practice | Complete for homework | Practice Exercises |
| Challenge #8-9 | Period 3 (optional) | Optional extension | Practice Exercises |
| Trace Exercise | Period 1 or 2 wrap-up | — | Trace Exercise |
| GitHub Classroom | — | Due end of week | GitHub Classroom |
Additional Resources
- Pattern programming sheet (6 patterns: triangle, chessboard, diagonal, cross, hollow square, number pyramid)
- Guessing game starter code (enrichment activity)
- Scanner buffer clearing reference sheet (
nextInt()/nextLine()skip bug)