Introduction

In this article, we will learn how to control the flow of execution of our program, using loops. Basically, loops perform the operations where we need to run a query multiple times. However, it is not necessary. Loops are very common in all programming languages.

What is Range?

In this example, we simply make a range from 0 to 100, and then print its end index using its built-in method. We use the same for start index. Then, we count our range if numbers are present or not. Also, remember that 0 is also present in this sequence because we started from 0.

Code

var sequenceNumber = 0...100

sequenceNumber.endIndex
sequenceNumber.startIndex
sequenceNumber.count


What is For Loop?

Syntax

for <INTIAL CONDITION >; <LOOP CONDITION>;<ITERATION CODE>
{
<LOOP CODE>
}

Here is the example to clear your concept and to show the new feature in Swift, i.e., we can also see a graph of our loop.

code

Here is the example in which we simply take a constant number and declare it with 5. Then, declare a new variable, a sum that is initialized with 0. Then, we declare a for loop body and initialize it with variable i. Now, increment the sum variable by 1.

Code

let number=5,

var sum=0
for var i = 1; i<=number; i+=1 {
sum += i
}

What is While Loop?

Syntax

while <CONDITION> {
<LOOP CODE>
}


Here is the example to clear your concept.

graph

In this example, we simply declare a variable and in While Loop, we set the condition that if the addition is less than 1000, it's incremented in addition variable. It runs 11 times in the example.

Code

var addition = 1
while addition < 1000
{
addition=addition+99
}


Repeat While Loop

Syntax

repeat {
<LOOP CODE>
} while <CONDITION>

code

In this example, you see that the code can’t run because we declare the sum as 1 and in while condition we declare that the sum is less than one. The condition is false. So, the loop can’t run.

Code

var sum = 1
repeat
{
sum = sum + 1
} while sum < 1


Main Points