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?
- A sequence of numbers, which you want to represent in your coding, is called Range. For example, you start with 0 and end with 100. This type of sequence are needed to be declared with Range. Here is the example to clear your concept:
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?
- In Swift, loops are similar like in other languages. It is the way of executing a code for multiple times. In For Loop, these three things are mandatory - initial condition, final condition and iteration.
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.
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?
- The next loop is While Loop, which iterates only when the certain condition is true. That is why, it is called While Loop.
Syntax
while <CONDITION> {
<LOOP CODE>
}
Here is the example to clear your concept.
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
- It is different from While Loop only in one aspect. The condition is evaluated at the end of the loop rather than at the beginning.
Syntax
repeat {
<LOOP CODE>
} while <CONDITION>
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
- Using Range, you can create a sequence of numbers and incrament it from one value to another.
- Labeled statements are those where we use break keyword.