Swift While and Repeat-While Loops Example

1. Introduction

In Swift, the while and repeat-while loops provide a way to execute a block of code as long as a specified condition remains true. These loops are ideal when the exact number of iterations is unknown beforehand.

2. Source Code Example

// The while loop example
var counter = 1
while counter <= 5 {
    print("The value of counter is \(counter)")
    counter += 1
}

// The repeat-while loop example
var anotherCounter = 1
repeat {
    print("The value of anotherCounter is \(anotherCounter)")
    anotherCounter += 1
} while anotherCounter <= 5

Output:

The value of counter is 1
The value of counter is 2
The value of counter is 3
The value of counter is 4
The value of counter is 5
The value of anotherCounter is 1
The value of anotherCounter is 2
The value of anotherCounter is 3
The value of anotherCounter is 4
The value of anotherCounter is 5

3. Step By Step Explanation

1. The while Loop:

- Before each iteration, this loop checks the condition. If the condition evaluates to true, the code block inside the loop will be executed.

- We initiate a variable named counter with a value of 1.

- The while loop checks if the counter is less than or equal to 5. If true, it enters the loop, prints the value, and then increments the counter by 1.

- This process continues until the counter exceeds 5, at which point the loop terminates.

2. The repeat-while Loop:

- This is similar to the while loop but with one crucial difference: the condition is checked after the loop's code block is executed. This ensures that the loop's contents are executed at least once, regardless of the condition.

- We have a variable anotherCounter initiated to 1.

- The code block inside the repeat is executed first, printing the value and incrementing anotherCounter.

- After executing the code block, the loop checks the condition. If anotherCounter is still less than or equal to 5, it repeats the process. 

In summary, while both loops are used for repeated execution based on a condition, the key difference lies in when the condition is evaluated. The while loop evaluates before execution, and the repeat-while loop evaluates after executing its block once.


Comments