3.2.2 - Count-controlled iteration (VB.NET)
Use a known repetition count to write and trace VB.NET loops. Native exam answers are written without Run; the optional Python demonstration explores the same accumulator idea.
Choosing the repetition count
A count-controlled loop repeats a body a number of times determined when the loop begins.
Iteration
Repeated execution of a group of instructions. Count-controlled, or definite, iteration uses a known repetition count.
If a quiz contains four rounds, a For loop can display each round number:
For round As Integer = 1 To 4
Console.WriteLine("Round " & round)
Next
The body executes for 1, 2, 3 and 4. VB.NET's To endpoint is inclusive. The default step is +1; For number As Integer = 6 To 2 Step -2 visits 6, 4, 2. A positive-step loop whose start exceeds its end performs no iterations. For i As Integer = 1 To 0 therefore has an empty body run.
Iteration combines with sequence inside its body and selection where a repeated decision is needed. Place an instruction inside the loop when it must happen for each round, and after Next when it must happen once after all rounds. Do not modify the loop counter yourself to simulate extra updates; Next already advances it. Use a separately declared result if you need data after the loop; do not rely on counter values after a loop, especially when translating supplied AQA pseudocode.
Tracing counters and accumulators
An accumulator stores a result built across successive iterations rather than replacing it with the last input.
Dim total As Integer = 0
For round As Integer = 1 To 3
Dim score As Integer = CInt(Console.ReadLine())
total = total + score
Next
Console.WriteLine(total)
With scores 4, 7, 2, trace the state after each addition:
| Round during the body | New score | Total after update |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 7 | 11 |
| 3 | 2 | 13 |
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account