Swift Repeat-While Loop

In swift, the repeat-while loop is same as while loop but only the difference is, it will execute the defined statements first then it will perform the condition check and it will execute the statements repeatedly till the defined condition TRUE.

 

The repeat-while loop will execute the statements at least once even if the defined condition fails (FALSE) because it will execute the statements first then it will perform condition check but in while statements execution will perform only when the defined condition is TRUE.

 

Note: The repeat-while loop in swift programming language is same as do…while loop in other programming languages.

Now we will see the functionality of repeat-while loop in a swift programming language using an algorithm diagram. 

Swift Repeat-While Loop Flow Diagram

Following is the swift repeat-while loop statement flow diagram to represent how the functionality of repeat-while loop will work in a swift programming language.

 

swift repeat while loop flowchart diagram with examples

 

If you observe above swift repeat-while loop flow diagram first it will execute statements then it will perform condition check and it will execute the statements repeatedly till the defined condition fails.

Syntax of Swift Repeat-While Loop

Following is the syntax of defining repeat-while loop in a swift programming language.

 

repeat

{

// your statements

} while condition

If you observe above swift repeat-while loop syntax first it will execute the statements and then it will perform condition check.

 

Now we will see how to use the repeat-while loop in a swift programming language with examples.

Swift Repeat-While Loop Example

Following is the simple example using repeat-while loop in swift to execute statements repeatedly till the condition TRUE.

 

var sum = 2

 

repeat

{

print(sum)

sum = sum + 2

} while sum < 10

If you observe the above repeat-while loop example first it will execute the defined statements and then it will perform condition check and execute statements continuously till the defined condition is TRUE.

 

When we execute the above program in swift playground we will get result like as shown below.

 

2

4

8

10

This is how we can use a repeat-while loop in swift programming language to execute statements at least once even if the defined condition is FALSE based on our requirements.