Repeat-while loops

A variant of the while loop is called the repeat-while loop. It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning.

You construct a repeat-while loop like this:

repeat {

<LOOP CODE>

} while <CONDITION>

Here’s the example from the last section, but using a repeat-while loop:

var sum = 1

repeat {

sum = sum + (sum + 1)

} while sum < 1000

In this example, the outcome is the same as before. However, that isn’t always the case — you might get a different result with a different condition.

Consider the following while loop:

var sum = 1

while sum < 1 {

sum = sum + (sum + 1)

}

And now consider the corresponding repeat-while loop, which uses the same condition:

var sum = 1

repeat {

sum = sum + (sum + 1)

} while sum < 1

In the case of the regular while loop, the condition sum < 1 is false right from the start. That means the body of the loop won’t be reached! The value of sum will equal 1 because the loop won’t execute any iterations.

In the case of the repeat-while loop, however, sum will equal 3 because the loop will execute once.

results matching ""

    No results matching ""