Justify why one loop structure may be better suited to solve a problem than the others

Cambridge A‑Level Computer Science (9618) – Topic 11.2 Constructs: Loop Structures

Learning Objective (AO1 + AO2 + AO3)

Explain, analyse and justify why one loop structure (for, while or do…while) is the most appropriate choice for a given problem. Use clear pseudocode, state pre‑ and post‑conditions, and discuss algorithmic efficiency where relevant.

Syllabus Mapping

  • 11.2 Constructs – iteration (loop) structures.
  • 9.1 Algorithm design – step‑wise refinement, flow‑chart ↔ pseudocode.
  • 9.2 Analysis – pre‑conditions, post‑conditions, time‑complexity.

1. Overview of the Three Loop Constructs

Loop Typical C‑like Syntax When the Test Is Evaluated Guarantees Typical Use‑Case
for
for (initialisation; test; update) {
    // body
}
Before each iteration (pre‑condition) Zero or more executions; loop variable scoped to the loop Known, fixed number of repetitions (e.g., iterating over an array)
while
while (test) {
    // body
}
Before each iteration (pre‑condition) Zero or more executions; body may be skipped entirely Data‑driven condition where the number of repetitions is not known in advance
do … while
do {
    // body
} while (test);
After each iteration (post‑condition) At least one execution; body always runs once Situations that require a mandatory first pass (e.g., menu‑driven programs)

2. Choosing the Right Loop – Decision Guide

  1. Known, fixed number of repetitions
    • Prefer a for loop.
    • Pre‑condition: the loop counter satisfies the test before the first iteration.
    • Complexity: O(n), where n is the bound.

    Example – Print the first n Fibonacci numbers

    for (int i = 1; i <= n; i++) {
        // calculate and display Fibonacci(i)
    }
    
  2. Indeterminate repetitions, condition‑driven
    • Prefer a while loop.
    • Pre‑condition expressed directly in the test; the body may never execute.
    • Complexity: depends on how many times the test evaluates true (≤ n).

    Example – Read values until sentinel -1 is entered

    int value = readNext();
    while (value != -1) {
        // process value
        value = readNext();
    }
    
  3. At least one execution required
    • Prefer a do…while loop.
    • Post‑condition tested after the first pass, guaranteeing one execution.
    • Complexity: same as a while loop plus the guaranteed first iteration.

    Example – Simple menu‑driven program

    int choice;
    do {
        displayMenu();
        choice = getChoice();
        // handle the choice
    } while (choice != EXIT);
    

3. Pre‑condition / Post‑condition Summary

Loop Pre‑condition (what must be true before the first iteration) Post‑condition (what is true when the loop terminates)
for Initialisation performed; test evaluates true for the first iteration (if any). After the final update the test is false; loop variable holds the value that caused termination.
while Test evaluated before the first iteration; may be false → body never runs. Loop exits when the test becomes false.
do…while None – the body runs unconditionally once. Test evaluated after each iteration; loop repeats while the test is true.

4. Nested Loops & Control Variables

  • Nested loop definition: a loop placed inside the body of another loop. Useful for two‑dimensional data (matrices) or when an inner repetition depends on an outer iteration.
  • Each loop must have its own control variable(s) to avoid accidental interference.
  • Overall time‑complexity is the product of the individual complexities (e.g., two nested for loops → O(n²)).

Example – Multiplication table of size 

for (int i = 1; i <= n; i++) {          // outer loop – rows
    for (int j = 1; j <= n; j++) {      // inner loop – columns
        print(i * j + "\t");
    }
    println();                         // new line after each row
}

5. Common Errors Checklist (AO2/AO3)

  • Off‑by‑one errors – using <= instead of < (or vice‑versa) in the test.
  • Infinite loops – forgetting to update the control variable or using a condition that can never become false.
  • Uninitialised or out‑of‑scope counters – declaring the loop variable outside the loop when it should be local.
  • Incorrect loop type – choosing do…while when the body must not run for an empty data set.
  • Array‑index out‑of‑bounds – iterating beyond array.length‑1.
  • Mismatched pre‑/post‑conditions – not stating what must hold before/after the loop, leading to logical errors.

6. Detailed Justification Example – Searching a List

Problem: Find the first occurrence of target in an array list of unknown length.

int i = 0;
while (i < list.length && list[i] != target) {
    i++;
}
if (i < list.length) {
    // target found at index i
} else {
    // target not present
}
  • Why while is optimal
    • The number of iterations depends on data; the loop stops as soon as the target is found or the end is reached.
    • If list.length == 0, the test fails before any body execution, preventing an out‑of‑bounds error.
    • The combined termination condition (i < list.length AND list[i] != target) is naturally expressed in the while header, keeping the algorithm readable.
    • Time‑complexity: O(k), where k ≤ n (position of the target or the array length).
  • Using a for loop would obscure the early‑termination nature and require an extra break statement.
  • Using a do…while loop would guarantee one execution, risking an out‑of‑bounds access when the array is empty.

7. Comparison Table – When to Use Each Loop

Loop Ideal Situation Key Characteristics Typical Use‑Case Complexity Note
for Known, fixed number of iterations Initialisation, test, update all in the header; counter scoped to the loop Iterating over arrays, counting loops, generating sequences O(n) where n is the bound
while Indeterminate repetitions; loop may never run Pre‑condition test; body may be skipped entirely Reading input until a sentinel, searching until a match, validating data O(k) where k ≤ n (depends on data)
do…while At least one execution required Post‑condition test; body always runs once Menu systems, repeat‑until validation, prompting for correct input O(k + 1) – same as while plus guaranteed first pass

8. Key Points to Remember (AO1)

  • Match the loop type to the problem nature:
    • Fixed count → for
    • Data‑driven condition → while
    • Mandatory first pass → do…while
  • Always state the pre‑condition (what must be true before the first iteration) and the post‑condition (what is true when the loop finishes).
  • Consider algorithmic efficiency – a loop with a known bound is easier to analyse and often yields a tighter complexity bound.
  • Watch for off‑by‑one errors, infinite loops, and the scope of control variables.
  • When nesting loops, keep each control variable distinct; overall complexity multiplies (e.g., two nested for loops → O(n²)).

9. Suggested Diagram (for visual learners)

Flowchart illustrating the entry/exit points of for, while and do…while loops, highlighting the difference between pre‑condition and post‑condition testing.

Create an account or Login to take a Quiz

93 views
0 improvement suggestions

Log in to suggest improvements to this note.