Swift – While Loop
Last Updated :
12 Sep, 2022
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:
flow diagram
Example 1: Swift program to print GeeksforGeeks 7 times
Swift
var i = 2
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
var i = 1, n = 20
print ( "Even numbers:" )
while i <= n{
if (i % 2 == 0){
print (i)
}
i = i + 1
}
|
Output:
Even numbers:
2
4
6
8
10
12
14
16
18
20
Share your thoughts in the comments
Please Login to comment...