Swift - While Loop



A while loop statement in Swift programming language repeatedly executes a designated statement as long as a given condition remains true. The condition is very crucial in the while loop it prevents the loop from becoming an infinite loop. So always check the condition in the while loop.

The key point of a while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Syntax

The syntax of a while loop −

while condition
{
   statement(s)
}

Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop.

Flow Diagram

The following flow diagram will show how the while loop works −

While Loops

Example

The following Swift program uses the comparison operator < to compare the value of the variable index against 20. While the value of the index is less than 20, the while loop continues executing a block of code next to it and as soon as the value of the index becomes equal to 20, it comes out.

import Foundation

var index = 10

// Here the loop continues executing until the index is less than 20  
while index < 20 {
   print( "Value of index is \(index)")
   index = index + 1
}

Output

It will produce the following output −

When executed, the above code produces the following result −

Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 15
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19

Example

Swift program to find the sum using a while loop.

import Foundation
var sum = 0
var num = 1

// Here the loop continues executing until num is less than equal to 9   
while num <= 9 {
   sum += num
   num += 1
}

print("Sum of numbers from 1 to 9 is: \(sum)")

Output

It will produce the following output −

When executed, the above code produces the following result −

Sum of numbers from 1 to 9 is: 45
Advertisements