4.1.1.2 - Definite, indefinite and nested iteration (VB.NET)
Learn to choose a repetition structure, follow changes to loop state and combine loops with selection without losing track of boundaries. Native VB.NET tasks are written only; this route is incomplete: runnable support pending.
Count-controlled loops and accumulation
Definite iteration repeats a known number of times; a count-controlled loop makes its start, end and step explicit. VB.NET's For includes its end value when the step reaches it. A loop from 1 To 4 with the default step 1 therefore executes four times.
Dim total As Integer = 0
For itemNumber As Integer = 1 To 4
total = total + itemNumber
Next
Console.WriteLine(total)
total is an accumulator: it combines each new value with the result so far. It must be initialised before the loop. If it were reset to zero inside the loop, it would retain only the last item instead of their sum.
| itemNumber during the body | total before addition | total after addition |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| 4 | 6 | 10 |
The displayed result is 10. Next updates the counter and tests whether another iteration belongs in the range; it is not an extra repetition after the end. For value As Integer = 8 To 2 Step -2 visits 8, 6, 4 and 2. With a positive step, a start above the end means zero iterations. Choose Step deliberately and do not manually alter the control variable inside the body.
A counter counts occurrences rather than adding the data values. It often increases by 1 only when a selection is true. Both accumulator and counter names should reveal their meaning, such as totalScore and passingCount. A subroutine may contain a loop, allowing the repeated operation to be reused.
Pre-test and post-test indefinite iteration
Indefinite iteration repeats until a condition determines that it should stop; the number of repetitions is not fixed in advance. Where the condition is tested changes whether the body can be skipped altogether.
A pre-test loop checks before entering its body. While condition ... End While and Do While condition ... Loop continue while the condition is True. This fragment displays 0, 1 and 2; after the last update, 3 fails the condition.
Dim attempts As Integer = 0
Do While attempts < 3
Console.WriteLine(attempts)
attempts += 1
Loop
A post-test loop executes the body before checking. It always enters once. Do ... Loop Until condition repeats while the ending condition is False and stops when it becomes True.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account