Swift - Repeat-While Loop
The Repeat-While Loop
The repeat-while loop is another version of while loop. It executes statements before checking the while conditions. Hence, it executes statements at least once and continues to repeat the loop as long as the while condition is true. It's functionality is same as do-while loop in C or C++.
Syntax
repeat { statements } while (condition)
Flow Diagram:
Example
In the example below, repeat loop is used to print numbers from 1 to 5.
var i = 1 repeat { print("i = \(i)") i = i + 1 } while(i < 6)
The output of the above code will be:
i = 1 i = 2 i = 3 i = 4 i = 5
Example:
Consider one more example, where the statements are executed once even if the while conditions are not fulfilled.
var i = 10 var sum = 0 repeat { sum = sum + i } while(i < 6) print(sum)
The output of the above code will be:
10