Swift While Loop
A loop is a block of code that allows you to repeat a certain task multiple times. The Swift programming language provides several types of loops, including the while
loop.
The while
loop allows you to repeat a block of code as long as a certain condition is true. The condition is checked at the beginning of each iteration of the loop. If the condition is true, the block of code is executed. If the condition is false, the loop is exited and the program continues executing the next line of code.
Syntax of the While Loop
The syntax of the while loop in Swift is as follows:
1while condition { 2 // code to be executed while the condition is true 3}
The condition
is the expression that is evaluated at the beginning of each iteration of the loop. The code block is executed as long as the condition is true.
Example: Printing Numbers Using While Loop
Let's see an example that prints numbers from 1 to 5 using the while
loop.
1var counter = 1 2while counter <= 5 { 3 print(counter) 4 counter += 1 5}
In this example, we initialize the variable counter
with the value 1
. The condition counter <= 5
is checked at the beginning of each iteration of the loop. If the condition is true, the block of code inside the loop is executed. Inside the loop, we print the value of counter
and increment it by 1
using the counter += 1
statement.
The output of the above program will be:
11 22 33 44 55
Example: Calculating the Sum of Digits Using While Loop
Let's see another example that calculates the sum of digits of a number using the while
loop.
1var number = 12345 2var sum = 0 3while number != 0 { 4 sum += number % 10 5 number /= 10 6} 7print("The sum of digits is: \(sum)")
In this example, we initialize the variable number
with the value 12345
and sum
with 0
. Inside the loop, we add the last digit of the number
to the sum
using the statement sum += number % 10
. Then, we remove the last digit from the number
using the statement number /= 10
. The loop continues until the number
becomes 0
.
The output of the above program will be:
The sum of digits is: 15