In this tutorial you will learn about the Swift Repeat While Loop and its application with practical example.
Swift Repeat While Loop
The repeat…while loop executes block of statements inside loop body first and then test the condition for next iteration and executes next only if condition is true. The repeat…while loop is much similar to swift while loop with one major difference, in repeat…while loop block of statements inside loop body executes at least once.
Swift Repeat While Loop Flow Diagram
Syntax:-
1 2 3 |
repeat { // loop body } while condition |
Here, loop executes block of statements inside loop body first and then test the condition provided along with while keyword for next iteration and executes next only if condition is true. Condition is a Boolean expression that results in either True or False, if it results in True then statements inside loop body are executed and condition is evaluated again. This process is repeated until the condition is evaluated to False. If the condition results in False then loop is terminated and control is transferred to next statement.
Example:-
1 2 3 4 5 6 7 8 |
var ctr:Int = 1 let maxCtr:Int = 5 print("W3Adda - Swift Repeat While Loop") repeat{ print("Hello World! Value Is :\(ctr)") ctr = ctr + 1 } while ctr <= maxCtr |
Here, we have initialized ctr and maxCtr to 1 and 5 respectively, in the next statement we have loop body inside the pair of curly brackets {} after repeat keyword, statements inside loop body are executed first then control is passed to the condition ctr <= maxCtr provided along with while keyword for next iteration. If the test condition returns True, then control is passed again to loop body for the next iteration. If the condition results in False then loop is terminated and control is transferred to next statement. Inside the loop body we have incremented the ctr value by one for each if the iteration. When we run the above swift program, we see the following output –
Output:-