The repeat-while loop

A repeat-while loop also contains a condition and a set of statements in curly braces, but it executes the statements first before checking the condition, repeating until the condition returns false. Here is what it looks like:

repeat {
code
} while condition == true

Type and run the following code:

// repeat loop
// set of statements is executed, then the condition is checked
var x = 0
repeat {
x += 5
print("x is (x)")
} while x < 50

Initially, x is set to 0. The statements inside the curly braces are executed. The value of x is incremented by 5, so now x contains 5, and x is 5 is printed to the Debug area. The x < 50 condition is checked, and since it returns true, the loop is repeated. The value of x is incremented by 5so now x contains 10, and x is 10 is printed to the Debug area. The loop is repeated until x contains 50, at which point x < 50 returns false and the loop stops.

The statements in the curly braces will be executed at least once, even if the condition is false, to begin with. Try changing the value of x to 100 to see this.

This concludes the section on loops.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.35.77