B2.3.3 Construct programs that utilize looping structures to perform repeated actions.
• Types of loops, including counted loops and conditional loops, and appropriate use of each type
• Conditional statements within loops, using Boolean and/or relational operators to govern the loop’s execution
The Big Idea
In programming, looping structures allow us to execute a block of code multiple times, often with changing conditions or counters. Instead of writing the same instructions repeatedly, loops enable efficient, concise, and flexible repetition of actions—a core concept in all computational processes.
There are two broad categories of loops:
- Counted loops: repeat a specific number of times.
- Conditional loops: repeat while a condition remains true.
Effective use of loops—especially with conditional logic—allows programs to process data sets, interact with users, and perform algorithmic operations in a scalable way.
1. Types of Loops
A. Counted Loops (Definite iteration)
Counted loops execute a fixed number of times, often using a loop control variable.
Python Example:
for i in range(5):
print("Iteration:", i)
Java Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
- Commonly used when the number of iterations is known ahead of time.
- The loop variable (
i) controls how many times the loop runs. - These are known as
forloops in most languages.
B. Conditional Loops (Indefinite iteration)
Conditional loops repeat until a condition becomes false. These are used when the number of repetitions is not known in advance.
Python Example:
password = ""
while password != "open123":
password = input("Enter password: ")
Java Example:
Scanner sc = new Scanner(System.in);
String password = "";
while (!password.equals("open123")) {
System.out.print("Enter password: ");
password = sc.nextLine();
}
- These are typically
whileloops. - Loop continuation depends on Boolean or relational expressions.
2. Loop Variants and Their Use Cases
| Loop Type | Syntax Form | Best Use Case |
|---|---|---|
for loop | Count-controlled | When the number of iterations is known |
while loop | Condition-controlled | When looping until a condition changes |
do-while loop (Java only) | Executes at least once | When the body must run before the condition is checked |
Java do-while Example:
int num;
do {
num = scanner.nextInt();
} while (num <= 0);
3. Using Conditional Statements Within Loops
Inside a loop, if, elif, else (Python) or if, else if, <strong>else</strong> (Java) can be used to modify control flow, such as filtering values, breaking loops, or skipping iterations.
Example: Filtering Odd Numbers (Python)
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
Example: Early Exit on Match (Java)
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
System.out.println("Found!");
break;
}
}
4. Boolean and Relational Conditions in Loops
Loops often rely on relational and Boolean logic for continuation or branching.
Python Example:
while age < 18 or not has_permission:
print("Access denied.")
# request age or permission
Java Example:
while (score >= 0 && score <= 100) {
System.out.println("Valid score");
// get new input
}
| Operator Type | Examples | Use |
|---|---|---|
| Relational | <, <=, >, >=, ==, != | Compare values |
| Boolean | and, or, not (Python) / &&, ||, ! (Java) | Combine or invert relational expressions to form compound conditions |
5. Common Errors and How to Avoid Them
| Mistake | Description |
|---|---|
| Infinite loops | Forgetting to update loop control variables or incorrect condition (e.g. while True: with no break) |
| Off-by-one errors | Misunderstanding range limits (e.g. i < n vs i <= n) |
| Incorrect condition logic | Using or instead of and (or vice versa), leading to loops that always run or never run |
| Missing initialization | Using a loop variable that was not initialized before the loop |
| Altering loop counter inside loop body | Can cause unexpected behavior or missed iterations |
6. Example: Accumulate Input Until Sentinel Value
Python:
total = 0
num = int(input("Enter number (-1 to quit): "))
while num != -1:
total += num
num = int(input("Enter number (-1 to quit): "))
print("Total:", total)
Java:
Scanner scanner = new Scanner(System.in);
int total = 0;
int num = scanner.nextInt();
while (num != -1) {
total += num;
num = scanner.nextInt();
}
System.out.println("Total: " + total);
This pattern is called a sentinel-controlled loop.
Summary
| Feature | Description |
|---|---|
| Counted loop | Loop that runs a fixed number of times (e.g. for loop) |
| Conditional loop | Loop that runs based on a condition (while, do-while) |
| Control variables | Used to limit and manage iteration |
| Conditional statements | Guide decisions within the loop (if, else) |
| Boolean logic | Governs when to continue, break, or skip |
| Common errors | Infinite loops, off-by-one, improper condition updates |
Final Thoughts
Looping structures allow for structured repetition, which is a foundational concept in procedural and algorithmic programming. Whether you're iterating over datasets, accumulating results, validating user input, or searching for a condition, loops provide the mechanism for efficient repetition and control. Choosing the correct type of loop—and controlling it with properly designed Boolean logic—is essential for writing robust, correct, and performant software.