Open In App

Swift – While Loop

Last Updated : 12 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Just like other programming languages, the working of the while loop in Swift is also the same. It is used to execute a target statement repeatedly as long as a given condition is true. And when the condition becomes false, the loop will immediately break and the line after the loop will execute. While loops are used as an alternative to for-in loops when the number of iteration is not known. This loop executes a set of statements until a false condition occurs. This loop is generally used when we don’t know the number of iterations. That means when we don’t know how many times we have to loop we will use while loop their instead of for loop because this loop will repeat the code as long as the condition is true.

Syntax:

while condition 
{
    // Body or while loop and Statements
}

Where the condition may be an expression like x > 2 and statement(s) may be a single line of code or multiple lines of code.

Flow chart of while loop:

while loop in swift

flow diagram

Example 1: Swift program to print GeeksforGeeks 7 times

Swift




// Creating and initializing variable
var i = 2
 
// Iterate the while loop till i less than equal to 8
while i <= 8{
   print("GeeksforGeeks")
   i = i + 1
}


Output:

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Example 2: Swift program to print the even and odd numbers using while loop

Swift




// Creating and initializing variables
var i = 1, n = 20
 
// Iterate the while loop
print("Even numbers:")
while i <= n{
    // It will check the number is
    // completely divisible by 2 or not
    if (i % 2 == 0){
        print(i)
    }
    i = i + 1
}


Output:

Even numbers:
2
4
6
8
10
12
14
16
18
20

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads