4.1.1.2 - Definite, indefinite and nested iteration (C#)
Iteration repeats a useful sequence of statements. Learn when to use count-controlled, pre-test and post-test loops, then track the state of nested loops without losing the purpose of each counter.
C# route status: incomplete: runnable support pending. Source is written and traced here with no Run control; runnable support is still required for complete onscreen Paper 1 preparation.
Count-controlled loops
Definite iteration repeats a known number of times, making it suitable for a fixed batch of values or array elements.
A C# for loop puts the initialisation, continuation test and update together. Inside Main, this fragment totals four scores:
int[] scores = new int[] { 3, 7, 4, 6 };
int total = 0;
for (int index = 0; index < scores.Length; index++)
{
total = total + scores[index];
}
Console.WriteLine(total);
Initialisation runs once. Before each body execution the condition is tested; if true, the body executes and then index++ increments the counter. If false, the loop ends. The successive indices are 0, 1, 2, 3. After those iterations total is 3, 10, 14, 20. At index = 4, the condition is false and no element is accessed. <= scores.Length would attempt an out-of-range index.
The accumulator total must start at zero before the loop, so it retains earlier contributions. Reinitialising it inside the loop would lose them. The counter index is declared for the loop and is not accessible afterwards. for (int number = 1; number <= 5; number++) instead performs five iterations numbered 1–5: the chosen start and boundary must agree with the requirement.
All three imperative principles can work together: sequence initialises the total, iteration visits scores, and selection such as if (scores[index] >= 5) can include only certain values. A subroutine can perform the same batch calculation whenever called. foreach (int score in scores) is another useful way to visit each element when its index is not needed.
Pre-test and post-test loops
Indefinite iteration stops when a condition changes, rather than after a known fixed count.
Pre-test and post-test iteration
A pre-test loop tests before its body, so the body can execute zero times. A post-test loop tests after its body, so it executes at least once.
In C#, while is pre-test and do ... while is post-test. Both continue while their written condition is true. That differs from a pseudocode REPEAT ... UNTIL finished convention, which stops when finished becomes true; translating it to C# requires a continuation condition such as !finished.
int remaining = 0;
while (remaining > 0)
{
Console.WriteLine(remaining);
remaining--;
}
int attempts = 0;
do
{
attempts++;
} while (attempts < 3);
Console.WriteLine(attempts);
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account