5. Master Loops
“Loops”, the ultimate tool for repetitive tasks in programming.
Before we dive into how to use loops, let’s first understand why loops are needed. So far, the programs we saw in the previous tutorials focused on the ‘do this, that, and finish’ approach.
Imagine we need to write a program that can print all the numbers from 1 to 5. How are we going to do it?
From what we already know, we can write a simple program as shown below to print the values from 1 to 5:
This approach can work up to some extent, but when we have a hundred lines to print or do a certain task a thousand times, well, that becomes a bit of a problem; right?
That’s when loops come to the rescue!
Using loops, we can simplify the repetitive tasks, and have more control over them. Loops in C (or any other programming language) help us repeat a block of code until a certain condition is met.
There are 3 main types of loops available in C that will help us with such tasks:
for loop
while loop
do-while loop
How does a loop work?
Although those three types of loops sound complicated, they are meant to do pretty much the same thing, but in a slightly different way. In a nutshell, all the loops work in the following order:
When we enter the loop, a condition is evaluated to see if it’s true or false. The loop will continue to run if and only if the condition is true. Then the loop will execute the lines inside, and come back to the beginning to evaluate the condition again. This process repeats until the loop condition becomes false. If so, the program will then exit the loop.
The first type of Loop that we will be talking about is a “for loop”.
For loop
A “for loop” is used when we know exactly how many times our code should run. Let’s have a look at our first example, the task where we had to print the numbers from 1 to 5:
Hit the run button above to see the output in the console.
Now let’s break down the code above, and try to understand what each line does. Since we already discussed the #include line and the int main(void) line already, let’s jump straight into business!
for(int i=1; i<=5; i++)
This is the most important line of our loop, the loop definition. If we take a closer look, we can see that there are three main parts inside the brackets. Let’s name them as for(A; B; C) Note that all these three code segments within the brackets are separated by colons. This is a must for each for() loop. Now let’s discuss what’s in the loop statement in detail.
A is called a loop initialization statement. This line is called exactly once, and we use that line to create a new variable named ‘i’ of type ‘int’, and initialize it to a value of ‘1’.
B is called the condition or the test expression. This is the most important part of the loop as this is what decides if the loop should continue to run or not. This basically says ‘continue the loop as long as ‘i’ is less than or equal to 5’. Easy, right?
C is called the update statement and is equally important as the test expression since this is the variable that the test expression checks each time the loop completes one of its cycles. (run once, increase ‘i’ by one, check if ‘i’ is less than ‘5’ if it is, run the loop body again)
Therefore, we MUST ensure that this variable we are interested in, ‘i’, is incremented after every cycle of the loop. The code segment in C is always executed after the loop executes once. In this case, if you remember what we learned in our previous tutorial on operators, ‘i’ is incremented once per each loop iteration.
After the loop definition, the curly brackets begin. Now, whatever we include in between these two curly brackets is going to be executed each time the loop repeats. In our case, the loop is going to print the value of ‘i’ each time the loop iterates. Where does this ‘i’ come from? Since it’s the loop variable of the loop itself, we can simply use it as a regular variable inside the loop.
You might have some questions regarding this ‘for() loop’:
Can we define the loop variable within the loop?
Yes, of course. For quick, one-off type loops where we won’t be needing the loop variable outside the loop, we can simply use for(int i=1; i<=5; i++) instead of for(i=1; i<=5; i++). But, keep in mind that if we declare the variable within the loop definition, the variable ‘i’ will only be available within the loop, because its scope will be limited.
Should ‘i’ or the loop variable need to be incremented exactly once?
No, you can perform any form of increment/decrement to the loop variable. But, remember; this affects how many times our loop will iterate.
We saw that this only runs a defined number of cycles. Can we run a for() loop infinitely?
Yes. if we just use for(;;), the loop will run endlessly. But, there’s a better way of doing this, the while() loop; which we will talk about next.
Can we use a loop within a loop?
Yes. Those are called ‘nested loops’ and we’ll be discussing them in a later tutorial.
Before we move onto the while() loop, it’s time for a quick challenge:
2. While loop:
We discussed how we can use the “for loop” to repeat a task a given number of times. Now let’s see how we can do a certain task while a certain condition is TRUE.
The while() loop can be considered as a more simplified version of the for() loop, which we can use to monitor a condition to keep the loop running.
Let’s start with a small example, where we want to create a program that would print the numbers from 5 to 0.
The loop condition is inside the brackets (d >= 0) and the loop will evaluate this both at the beginning and after each cycle. As we are decreasing the value of ‘d’ by one in each loop iteration, ‘d’ will eventually become less than 0. This will make the condition FALSE and the loop will then exit.
Note: that if we do not change the value of ‘d’ within the loop, the loop condition will always be TRUE and the loop will run endlessly!
The ‘infinite’ loop using while():
We can also write a loop that deliberately repeats forever. We only have to make the loop condition always TRUE. We can do just that by replacing the loop condition with any positive number. But, as a convention, we use ‘1’ for infinite loops as shown below:
For this example, we put ‘1’ as the loop condition. If you remember what we discussed at the top of this example, in order to continue a loop, the loop condition must always be TRUE. But isn’t ‘1’ considered to be TRUE in computer logic? Yes! Exactly! By putting ‘1’ as the loop condition, we’re letting the while() loop think that the loop condition is ALWAYS TRUE. So the loop will continue indefinitely because no one is changing that condition.
Time for a quick quiz!
3. Do-while loop:
The do-while() loop in C is another version of the while() loop and is often overlooked by many developers. It’s very similar to the while() loop, but has one major difference when comparing them:
The while() loop checks the condition before executing the loop body, and the do-while() loop executes the loop body at least once before checking the condition.
Let’s see an example of a do-while() loop in action:
As we discussed previously, when a do-while loop is reached, the content of the loop (the body) is run at least once even before the condition is checked for true or false. Therefore, even though the loop condition (is ‘a’ equal to 0?) is FALSE, we see one print statement: Value of ‘a’ is: 5. And then only the loop tries to see if the condition is true or false.
If we were to use a while loop instead of the do-while loop, the loop body will never execute. To make sure, let’s try to implement the same loop as a while loop. Try executing the below code and observe the output:
To our surprise, there will be no output! That’s because in a while() loop, the condition is always checked before entering the loop, and if it’s false in the first place, the while() loop will not continue!
To test your collective understanding of what we’ve learnt so far, let’s do a quick test.
for loop vs while loop vs do-while loop:
Challenges to try:
Now that you know how to use loops for repetitive tasks in C, you can try the following brain-teasers to better understand the concepts of looping in C, and take one more step forward in becoming a great programmer!
Write a program to print the sum of odd numbers from 0 to 100
Write a program to read 10 numbers from the user and display the sum of them
Convert the following for loop into a while loop: