3.2.2 - Condition-controlled iteration (VB.NET)

3.2.2 - Condition-controlled iteration (VB.NET)

Use conditions before or after a loop body and explain why a loop terminates. VB.NET answers remain written without Run; a labelled Python demonstration lets you explore a precondition.

Testing before repetition

A start-tested loop checks its condition before deciding whether to execute its body.

VB.NET
Dim remaining As Integer = 3
While remaining > 0
    Console.WriteLine(remaining)
    remaining = remaining - 1
End While

While means continue while the condition is true. The output is 3, 2, 1. After the last subtraction, remaining becomes 0; the next test is false and execution moves beyond End While. Starting with 0 produces no output because the body is never reached.

This is condition-controlled, or indefinite, iteration: continuation depends on a condition rather than a For count. It is especially useful when the required number of attempts is unknown, such as repeatedly asking for an acceptable menu choice. VB.NET also permits the start-tested form Do While remaining > 0 ... Loop. Both place the condition before the body.

Testing after repetition

An end-tested loop executes its body at least once before testing whether another pass is needed.

VB.NET
Dim choice As Integer
Do
    choice = CInt(Console.ReadLine())
Loop Until choice >= 1 And choice <= 3

The user gets an input opportunity even before choice contains an entered value. Until stops when its condition becomes true. Inputs 0, 4, 2 produce three passes, stopping on 2. A precondition While choice >= 1 And choice <= 3 would express the opposite continuation rule and could fail to start.

These equivalent end-tested forms emphasise the difference between a stopping and a continuation condition:

VB.NET
Do
    choice = CInt(Console.ReadLine())
Loop While choice < 1 Or choice > 3
Pseudocode
REPEAT
    choice ← USERINPUT
UNTIL choice ≥ 1 AND choice ≤ 3

Supplied AQA WHILE tests first; REPEAT ... UNTIL tests last and stops on true. An end-tested DO ... WHILE continues on true. Read the position and meaning of the condition, then answer in the requested language. VB.NET directly supports both positions; a language without a native end-tested form can reproduce its behaviour using a loop and exit.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account