B2.3.3 Construct programs that utilize looping structures to perform repeated actions.

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 for loops 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 while loops.
  • Loop continuation depends on Boolean or relational expressions.

2. Loop Variants and Their Use Cases

Loop TypeSyntax FormBest Use Case
for loopCount-controlledWhen the number of iterations is known
while loopCondition-controlledWhen looping until a condition changes
do-while loop (Java only)Executes at least onceWhen 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 TypeExamplesUse
Relational<, <=, >, >=, ==, !=Compare values
Booleanand, or, not (Python) / &&, ||, ! (Java)Combine or invert relational expressions to form compound conditions

5. Common Errors and How to Avoid Them

MistakeDescription
Infinite loopsForgetting to update loop control variables or incorrect condition (e.g. while True: with no break)
Off-by-one errorsMisunderstanding range limits (e.g. i < n vs i <= n)
Incorrect condition logicUsing or instead of and (or vice versa), leading to loops that always run or never run
Missing initializationUsing a loop variable that was not initialized before the loop
Altering loop counter inside loop bodyCan 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

FeatureDescription
Counted loopLoop that runs a fixed number of times (e.g. for loop)
Conditional loopLoop that runs based on a condition (while, do-while)
Control variablesUsed to limit and manage iteration
Conditional statementsGuide decisions within the loop (if, else)
Boolean logicGoverns when to continue, break, or skip
Common errorsInfinite 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.