Get up to 40 % extra points for free! More info
Save up to 80 % on our Swift e-learning courses. Only this week!

# Lesson 5 - Loops in Swift

In the previous exercise, Solved tasks for Swift lesson 4, we've practiced our knowledge from previous lessons.

In today's Swift tutorial, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

## Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

### The `for` loop

The `for` loop has a determined fixed number of steps and allows us to go through all the items of some group. The loop is executed for each item of the group, these executions are called iterations. The `for` loop syntax is the following:

`for (variable in group)`

First, let's have a look at how to do something more than once simply. For example, if we want to execute some code in a loop five times, we would generate a range of numbers from `1` to `5` and pass those to the loop. The code would be as follows:

```for (i in 1...5) {

}```

The code in the loop is executed 5 times. In the `i` variable, there are the values from `1` in the first iteration to `5` in the last one.

If you know the `for` loop from other languages, you probably noticed that in Swift it's more like the `foreach` loop.

Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:

```print("Knock")
print("Knock")
print("Knock")
print("Penny!")```

However, using loops, we no longer have to copy the same code over and over:

```for i in 1...3 {
print("Knock")
}
print("Penny!")```

The output:

```Knock
Knock
Knock
Penny!```

The loop will be executed three times; in the beginning `1` is stored in the `i` variable, the loop prints "Knock" and increases the `i` variable by 1. Then it does the same for `2` and `3`. Now let's try write `10` instead of `3` inside the loop declaration. The command will be run 10 times without us writing anything more. You can surely see that loops are powerful tools. We could modify the loop further, for example replace the `i` variable with an underscore:

```for _ in 1...3 {

}```

It doesn't affect the way the program works. We just made clear that the variable isn't important because we don't need it. This also removes the Xcode warning that alerts you of unused variables. Using an underscore, you can easily mark the variable as irrelevant. It's an information for you and other programmers.

Let's now take advantage of the fact that the variable is being incremented. Let's print numbers from one to ten. Since we don't want our output to be on separate lines, we'll use the `print()` function with a specified separator so that the values are printed next to each other:

```for i in 1...10 {
print(i, terminator:" ")
}```

The result:

`1 2 3 4 5 6 7 8 9 10`

We can see that the control variable has a different value after each iteration (step of the loop).

Now let's print a simple multiplication table that contains multiples of numbers from 1 to 10. All we need to do is to declare a loop from `1` to `10` and multiply the control variable with the current multiplier. It might look like this:

```print("Simple multiplication table using loops:")
for i in 1...10 {
print(i, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 2, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 3, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 4, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 5, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 6, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 7, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 8, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 9, terminator:" ")
}
print(" ")
for i in 1...10 {
print(i * 10, terminator:" ")
}
print(" ")```

The result:

```Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100```

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

```print("Here's a simple multiplication table using nested loops:")
for j in 1...10 {
for i in 1...10 {
print(i * j, terminator:" ")
}
print(" ")
}```

Makes a big difference, doesn't it? Obviously, we can't use `i` in both loops since they are nested. The variable `j` of the outer loop gains the values from `1` to `10`. During each iteration of the loop, another inner loop with the variable `i` is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable `j`. After each time the inner loop terminates it's necessary to break the line, it's done by `print(" ")`.

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:

```print("Exponent calculator")
print("===================")
print("Enter the base: ")
let a = Int(readLine()!)!
print("Enter the exponent: ")
let n = Int(readLine()!)!

var result = a
for _ in 1...n-1 {
result = result * a
}

print("Result: \(result)")
print("Thank you for using our exponent calculator")```

I'm sure we all know how powers (exponents) work. But just to be sure, let me remind that, e.g. 23 = 2 * 2 * 2. So, we compute an by multiplying the number `a` by the number `a` for n-1 times. Of course, the result must be stored in a variable. Initially, it'll have a value of `a` and this value will be gradually multiplying during the loop. We can see that our `result` variable in the loop body is normally accessible. If, however, we create a variable in a loop body, this variable will be no longer accessible after the loop terminates.

```Exponent calculator
===================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator```

Now, we know what some practical uses of the `for` loop are. Remember that it has a fixed amount of iterations. The loop variable is constant in every iteration, that means you can't change it (some languages allow it but it causes trouble).

### The `while` loop

The `while` loop works differently, it simply repeats the commands in a block while a condition is true. The syntax of the loop is the following:

```while condition {
// commands
}```

If you realized that the `for` loop can be simulated using the `while` loop, you are right However, the `while` loop is used for slightly different things. Typically, we call some method returning a logical `true`/`false` value, in the `while` loop condition. We could rewrite the original `for`-loop example to use the `while` loop instead:

```var i = 1
while i <= 10 {
println(i)
i += 1
}```

But this is not an ideal example of using the `while` loop. Let's take our calculator from previous lessons and improve it a little bit. We'll add an ability to enter more math problems. The program will not end immediately, but it'll ask the user whether they wish to calculate another math problem. Let's remind the original version of the code (this is the version with `switch`, but feel free to use the `if`-`else` version, it depends on you):

```print("Welcome to our calculator")
print("Enter the first number:");
let a = Double(readLine()!)!
print("Enter the second number:")
let b = Double(readLine()!)!

print("Choose one of the following operations:")
print("1 - addition")
print("2 - subtraction")
print("3 - multiplication")
print("4 - division")
let choice = Int(readLine()!)!
var result : Double = 0

switch (choice) {
case 1:
result = a + b
case 2:
result = a - b
case 3:
result = a * b
case 4:
result = a / b
default:
break
}

if (choice > 0) && (choice < 5) {
print("Result: \(result)")
} else {
print("Invalid choice")
}

print("Thank you for using our calculator.")```

Now, we'll put almost all the code into a `while` loop. Our condition will be that the user entered "yes", so we'll check the content of a `goOn` variable. This variable will be set to "yes" at the beginning since the program has to begin somehow, then we'll assign the user's input to it:

```print("Welcome to our calculator")
var goOn = "yes"
while goOn == "yes" {
print("Enter the first number:");
let a = Double(readLine()!)!
print("Enter the second number:")
let b = Double(readLine()!)!
print("Choose one of the following operations:")
print("1 - addition")
print("2 - subtraction")
print("3 - multiplication")
print("4 - division")
let choice = Int(readLine()!)!
let result = 0
switch (choice) {
case 1:
result = a + b
case 2:
result = a - b
case 3:
result = a * b
case 4:
result = a / b
default:
break
}
if (choice > 0) && (choice < 5) {
print("Result: \(result)")
} else {
print("Invalid choice")
}

print("Would you like to make another calculation? [yes/no]")
goOn = readLine()!
}
print("Thank you for using our calculator.")```

The result:

```Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtractions
3 - multiplication
4 - division
1
Result: 140.0
Would you like to make another calculation? [yes/no]
yes
Enter the first number:
-10.5
Enter the second number:```

Our application can now be used multiple times and is almost complete. In one of the next lessons, we'll show how to secure all inputs from the user.

You've already learned quite a lot! Nothing better than a little noggin exercise, right? In the following exercise, Solved tasks for Swift lesson 5, we're gonna practice our knowledge from previous lessons.

### Download

Downloaded 157x (135.68 kB)

Article has been written for you by Filip Němeček
Do you like this article?
No one has rated this quite yet, be the first one!

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!