Learning Swift – Control Flow [Loops]

learning swift control flow loops

 

Control Flow

“Control Flow” can be defined as the order in which statements in our programs gets executed.

Today we will delve into loops. Swift provides the for-in loop, while loop and repeat-while loop.

 

 

For-in Loops

If you know java or python, you would have encountered for loops. They are used to execute a block of statements multiple times.

The for loops in swift are written using the following syntax.

 

for index in range{
//statements
}

 

Example: to print the square of numbers from 1 to 5.

 

for number in 1...5 {
print("Square of \(number) is \(number*number)") 
}

 

“…” is a closed range operator. It is used to select the range of our iteration, inclusive of the start and end index. Here the range is {1,2,3,4,5}. Our variable number is initialized with the value “1”, ie the starting value of the range. Then the print statement is executed, and our number variable increments to “2”, then again the print statement. This loop is repeated until the value of index reaches the end of our range.

Hence our output stops at 5.

 

 

For-in loops are also used to iterate over arrays, strings, and dictionaries. Let’s see examples of few:

Consider an array of colors. We will print all colors present in the array using for loop.

 

var color = ["Red", "Green", "Yellow"]
for element in color{
print("\(element) is a color") 
}

 

Here element is our variable whose value changes and range is the color array. One by one all elements present in our array is printed.

 

control flow for-in loop array

 

Consider another example of a dictionary. Each dictionary item returns a key, value pair when iterated. And these keys and values can be used as variables in the for-in loop.

 

var groceryList = ["potatoes" : 4, "carrots" : 6, "onions" : 10]
for (vegetables, quantity) in groceryList{
    print("We need \(quantity) \(vegetables) from the market")
}

 

Here vegetables are keys and quantity are values in our dictionary. We use them as variables to iterate over the dictionary and print it.

 

control flow for-in loop dictionary

 

While loops

Next, comes the while loops. A while loop performs an iteration until the condition becomes false.

Swift provides two types of while loops – while and repeat-while.

 

Control Flow while loops

 

While

The while checks the condition at the start of the iteration.

First, the condition is checked, if it is true then only the statements are executed.

 

control flow while factorial

 

For our example, we will find the factorial of a number. Factorial of a number, let’s say 5 is calculated as a product of all the numbers from 5 to 1, ie 5,4,3,2,1. It is 120.

This can also be written as 5 * (5-1) * 3 * 2 * 1 or 5 * (5-1) * (5-2) * 2 * 1

This will lead to an algorithm like this:

We will start with two variables num and factorial. num will store our integer 5 and factorial will store our product. Initially, factorial will be set to 1.

The second step is, we will assign product of factorial and num to variable factorial.

The third step will decrease the number by 1

Next, we will check the condition whether num > 1 or not. Based on that steps 2 and 3 will be repeated.

Suppose at present we have num= 5 and factorial= 1

After step 2 and step 3, factorial will be equal to 1 * 5 ie 5 and num will be equal to 5-1 ie 4

Then in step 3, we check the condition whether num > 1, Currently num = 4 which is greater than 1. Hence the condition is true, so we will again do step 2 and 3. And so on until num becomes 1.

We can see that steps 2 and 3 are going to be repeated 4 times until num becomes 1.

Now, we will convert this algorithm to our code in swift.

We will take a variable number as 5 and another variable factorial with initial value as 1

Our while will have a condition “number>1” as we saw in our algorithm. We will calculate factorial as the product of factorial and number.

 

//while loops

//Factorial of a Number
var number = 5
var factorial = 1
while(number>1){
    factorial = factorial * number
    }

print("Factorial is \(factorial)")

 

Hold on a minute. I am getting an error. Something like “Execution was interrupted“. Also, see that this loop has executed 28 times. According to us, our loop should have executed only 4 times.

 

 

This happens because our number’s value is always 5. It is not decreasing. So the condition in while statement remains true always. When we write “number = number – 1“. The code runs smoothly. We can print the result. And it shows 120.

//while loops

//Factorial of a Number
var number = 7
var factorial = 1
while(number>1){
    factorial = factorial * number
        number = number - 1
}

print("Factorial is \(factorial)")

 

control flow factorial result

 

Also if you change the number, for example to 7. Now our factorial should be 5040.

And we can see our code also gives us the same output.

 

control flow factorial 7 result

 

If you want to check an individual value of factorial and number changing over each result. Click on show result. You might see a graph. To change to values, give a two finger click and select “value history”.

See the value changing. First, we have 7 which is the product of 7 and 1, then 42 which is the product of 6 and 7 and so on.

Similarly, you can see the decreasing value of a number by clicking on show result and again change to value history. Here the loop has run 6 times until number becomes 1.

 

control flow while values

 

control flow repeat while

 

Repeat-While

Next is repeat-while, which executes the code first and checks condition in the end.

 

For this one, we will write code to generate the binary representation of a decimal number.

The binary representation of 8 is “1000”. We do this using division. The number is divided by 2 and then the quotient is divided by 2 and so on until we get the quotient as 1 or 0. Simultaneously we save the remainders. Starting with this 1, we join all the remainders to finally have the binary representation.

The algorithm is like this:

We will have two variables: num storing the integer and bin which will store our binary string.

In the second step, we will first find the remainder by dividing num by 2 and add it to our binary string.

In the third step, we will divide num by 2.

In the final step, we check whether the number is not equal to zero, if yes, repeat step 2 or 3.

Suppose at present we have num equals 8

After step 2 and 3, bin = bin + 8%2 = “” + 0 = 0, and num = 8 /2 = 4.

Now when we check num != 0, it is not 0, and so step 2 and 3 will be repeated again and so on until num becomes 0.

When we see the final result, it is 0001, sort of reverse to our correct answer which is 1000.

control flow repeat while decimal to binary 2

 

We can change this by changing our expression for step 2 to bin = num%2 + bin. As you see here, now the final string becomes 1000.

Let’s do this in swift now:

First, we will initialize a decimalNumber variable. Then a string binary.

Inside our loop, first, we need to save the remainder as a string in our variable binary.

 

//repeat-while

//Binary representation of a number//
var decimalNumber = 8
var binary = ""
repeat{
    binary = (decimalNumber % 2) + binary
    decimalNumber = decimalNumber / 2
}while(decimalNumber != 0)

print("Binary representation is \(binary)")

 

But when we write binary += decimalNumber % 2, we get an error.

 

 

This error occurs because we are assigning an int value to a string variable. So we need to type cast this value into a string. Let’s do that.

 

//repeat-while

//Binary representation of a number//
var decimalNumber = 8
var binary = ""
repeat{
    binary = (String)(decimalNumber % 2) + binary
    decimalNumber = decimalNumber / 2
}while(decimalNumber != 0)

print("Binary representation is \(binary)")

 

Followed by while with a condition of decimalNumber != 0.

Now when we print binary, we get an output of “1000” as expected.

 

 

Let’s check for 25, the output should be “11001“. And we get the same output.

 

control flow result 2

 

Here also we can check the individual value using show result and then value history for both binary and decimal values.

 

control flow repeat while values

 

The code for this post can be found here.