Swift - repeat...while Loop
Understanding the repeat...while Loop in Swift
The repeat...while loop in Swift is a variation of the while loop, with a key distinction: it checks the loop condition after executing the loop body. This ensures that the loop runs at least once, regardless of whether the condition is initially true or false.
Syntax
repeat {
// Statements to execute
} while (condition)
Unlike for and while loops, where the condition is evaluated before execution, repeat...while loops ensure that the block runs at least once before checking the condition.
How the repeat...while Loop Works
The following flow diagram illustrates the working of a repeat...while loop:
- Execute the block of code.
- Check the loop condition.
- If true, repeat step 1; if false, exit the loop.
Example 1: Demonstrating a repeat...while Loop
Let's see a simple example that prints numbers from 5 to 15 using a repeat...while loop.
import
Foundation
var number
= 5
repeat {
print("Current number: \(number)")
number
+= 1
} while number
<= 15
Output
Current number: 6
Current number: 7
Current number: 8
Current number: 9
Current number: 10
Current number: 11
Current number: 12
Current number: 13
Current number: 14
Current number: 15
Example 2: Calculating Factorial Using repeat...while Loop
This example demonstrates how to calculate the factorial of a number using a repeat...while loop.
import Foundation
var num =
5
var factorial
= 1
var counter
= num
repeat {
factorial *= counter
counter -= 1
} while counter > 0
print(
"Factorial of \(num) is
\(factorial) "
)