# For vs While – a Beginner’s approach 1. Introduction

Computer programming is about solving problems and getting things done the right way. However, as a beginner, you don’t care how you do it as long as you get it done. It works so why bother tackling it in a completely different way after all?

I thought the same way when I first stumbled upon the loop statements in Swift because they all behave in exactly the same way. So I approached them reluctantly at first and soon asked myself how I lived without them.

The biggest challenge you face when discovering new programming paradigms is changing the way you think. This can be scary at first because you are used to doing things in a certain way and now you suddenly feel overwhelmed. It takes time and patience to get used to anything new but it’s worth doing it in the long run – being able to choose the right technique for a certain problem is a skill that any software developer should have in his toolbox.

OK, enough talking – let’s see what looping is all about.

2. The challenge

Your task for this tutorial is an easy one: compute the sum of all the numbers between 1 and 10. Before diving into coding, think how you would solve the problem and break it into steps. This is how I would do it:

• create the sum variable and assign its initial value;
• create the current number variable and assign its initial value;
• loop through the numbers and do two things for each iteration:
• extract the current number from the loop;
• add it to the sum;
• print the sum to the console;

That’s it for the algorithm – now let’s move on to the implementation.

3. The while implementation

Fire up Xcode and open a playground. Delete everything from it and add this line to kick things off:

`var sum = 0`

This creates a variable for the sum and sets its initial value – it is variable because you are going to change its value soon.

Note: There are many different ways of creating variables in Swift – this is the easiest approach of all because it uses type inference to determine the variable’s type – Int in this case.

Next create the current number variable and assign its initial value – the first number:

`var i = 1`

Now loop through the numbers with the while control flow statement using the less than or equal comparison operator:

```while i <= 10 {

}
```

The loop repeats itself as long as the current number is less than or equal to 10.

Note: You can also write the loop’s condition using the less than operator:

```while i < 11 {

}
```

There are two things you should do inside the loop for each number. First add the current number to the sum:

`sum += i`

Note: You could also do it like this – the initial approach is shorter because it uses the addition assignment operator:

`sum = sum + i`

Then update the current number variable with the new number using the addition assignment operator:

`i += 1`

Note: If you forget this step you end up with an endless loop since the condition is always true.

Note: You could also do it like this – the previous implementation is shorter though:

`i = i + 1`

Finally, print the sum to the console:

`print(sum, terminator: "")`

If you reverse the loop’s condition and body you get the repeat-while statement – let’s see it in action.

4. The repeat-while implementation

First reset the sum variable:

`sum = 0`

Next reset the current number variable:

`i = 1`

Now loop through the numbers with the repeat statement:

```repeat {

} while i <= 10
```

The loop repeats itself as long as the current number is less than or equal to 10 as before, but this time the condition is evaluated after the first iteration.

There are two things things you should do inside the loop for each number. First add the current number to the sum:

`sum += i`

Then update the current number variable with the new number:

`i += 1`

Finally, print the sum to the console:

`print(sum, terminator: "")`

Both loop types are similar:

• perform the initialisation;
• validate the condition at each iteration;
• perform the update for every iteration;

Let’s take a different approach and rewrite the whole thing in a more compact way with the for-in loop instead.

5. The for-in implementation

First reset the sum variable:

`sum = 0`

Next loop through the numbers with the for in statement using the closed range operator:

```for i in 1...10 {

}
```

The current number goes from 1 to 10 – a different value for each iteration.

Note: You can also write the loop using the half open range operator:

```for i in 1..<11 {

}
```

There is only one thing you should do inside the loop for each number – add it to the sum:

`sum += i`

Finally, print the sum to the console:

`print(sum, terminator: "")`

You’re almost there – let’s get rid of the current number variable. The for-each statement to the rescue!

6. The for-each implementation

First reset the sum variable:

`sum = 0`

Next loop through the numbers with the for each statement:

```(1...10).forEach {

sum += \$0

}
```

The loop’s body is a closure – a fancy word for anonymous function. The closure’s argument – \$0 – is the current number. You are going to add it to the sum for every iteration.

Note: The closure’s body can be written in many other ways in Swift – this is the simplest approach of all because it uses trailing closure syntax and shorthand argument names.

Note: You can’t use the break or continue statement to exit the current call of the body closure or skip subsequent calls.

Note: Using the return statement in the body closure will only exit from the current call to body, not any outer scope, and won't skip subsequent calls.

Finally, print the sum to the console:

`print(sum, terminator: "")`

That’s it – it can’t get any simpler than that!

Note: This tutorial deals with the imperative paradigm. Check out the reduce tutorial for the functional approach.

7. Conclusion

Both paradigms have their pros and cons – feel free to try them both and choose the one that suits you best. Happy coding! 🙂

Note: All the code in this tutorial was tested in a playground in Xcode 7.3 and Swift 2.2 (Download).

Posted in Swift
###### One comment on “For vs While – a Beginner’s approach”
1. iospaths says:

Well done.

Like