Published by Patrick Mutisya · 14 days ago
Justify why one loop structure may be better suited to solve a problem than the others.
If the exact number of iterations is known before the loop starts, a for loop is usually the clearest choice because the control variables are visible in one place.
Example: printing the first \$n\$ Fibonacci numbers.
for (int i = 1; i <= n; i++) {
// body
}
When the loop should continue until a condition that depends on data becomes false, a while loop is appropriate because the test is evaluated before each iteration.
Example: reading input until the sentinel value -1 is entered.
while (value != -1) {
// process value
value = readNext();
}
If the loop body must run at least once regardless of the initial condition, a do…while loop is the natural fit.
Example: presenting a menu and repeating until the user chooses “Exit”.
do {
displayMenu();
choice = getChoice();
// handle choice
} while (choice != EXIT);
| Loop Type | When to Use | Key Characteristics | Typical Use‑Case |
|---|---|---|---|
for | Known, fixed number of iterations | Initialisation, test, and update are in the header; loop variable scoped to loop | Iterating over arrays, counting loops |
while | Indeterminate repetitions; condition may become false before first iteration | Test evaluated before each iteration; body may never execute | Reading input until EOF, searching until a match is found |
do…while | At least one execution required; condition checked after body | Body always runs once; test after each iteration | User‑driven menus, repeat‑until validation loops |
Suppose we need to search a list of unknown length for a target value. The loop must stop as soon as the value is found, but it may also reach the end of the list without finding it.
Using a while loop:
int i = 0;
while (i < list.length && list[i] != target) {
i++;
}
if (i < list.length) {
// target found at index i
}
Why while is better here:
list.length == 0).i < list.length and list[i] != target) are naturally expressed in the test part of the while header.Using a for loop would require embedding the same complex condition in the header, which reduces readability, while a do…while loop would guarantee at least one iteration even when the list is empty, leading to an out‑of‑bounds error.
for, while, and do…while loops.