Introduction
Today we’re gonna learn once again about C’s control structures. This time we will take a look at loops in form of a while, do-while, and for loop.
While loops
Now we come to the loops. A loop is a block of code that is repeated until a certain condition is met. The while-loop is the most basic loop. Here is its structure:
while (CONDITION) {
CODE;
}You must ensure that the loop has an end. If it does not, the program loops forever, thus resulting in an infinite loop (e.g. while(1){}). Be careful about this.
break & continue
The loop can also be exited prematurely using a break or it can skip one iteration using a continue. These keywords are used in a situation when you either don’t want the entire clause to run or when some special condition has been met and you want to end the execution right there.
while (CONDITION) {
if (OTHER_CONDITION) {
break;
}
else if (OTHER_CONDITION) {
continue;
}
CODE;
}exercise
Let’s do a simple exercise on what we learnt so far:
#include <stdio.h>
int main() {
int i = 0;
while (i < 100) {
if (i > 2 && i < 40) {
continue;
} else if (i == 42) {
printf("42 encountered!\n");
break;
} else {
printf("%d\n", i);
}
i++;
}
return 0;
}Let’s analyze it a bit: (L = line)
- L4: define an integer variable
iwith value0 - L5: execute the code in
{}block whileiis less than100 - L6-7: If
iis greater than 2 and less than 40, continue with next iteration immediately - L8-10: If
iequals42, print the message and stop thewhile-loop - L11-13: If both ifs fail, print the current value of
i - L14: increment the value of
iby1
There is an error in the code that causes an infinite loop (try running it). Can you spot it? If i is greater than 2, the loop skips iteration, so the incrementation of i does not happen and so the i is stuck with the value of 2, forever looping…
How to fix it? We can try moving the incrementaiton (i++) to the start of the loop, but that changes its function a bit. Or we can add the incrementation right before continue. I will leave the fix for you 😊.
You should get a similar output, once it is fixed:
$ make ex1
cc -Wall -Wextra ex1.c -o ex1
$ ./ex1
0
1
2
40
41
42 encountered!Do-while loop
A loop very similar to a while-loop is a do-while-loop. It runs the code exactly once and then it checks the condition and acts as a regular while-loop. So even if the condition is false it ensures that the code runs at least once.
do {
CODE;
} while (CONDITION);For example:
do {
printf("I run exactly once!");
} while (0);Apart from its standard use, a do-while(0) loop is used to encapsulate a large C macro block that needs to be run as a single statement. This is an advanced use though and will not be covered here.
For loops
Another type of loop is a for-loop. You can say it is a special case of while-loop as you’ll see in a second. Here’s the structure and an example:
for (INIT; CONDITION; INCREMENT) {
CODE;
}for (int i = 0; i < 10; i++) {
printf("%d", i);
}It consists of three parts:
- INIT – Firstly, this part is run once when the loop is initialized. It serves to set up the loop. In this case it sets
ito zero. - CONDITION – Next the CONDITION expression is checked. If it’s false (0) the next steps are skipped and the loop is finished. Otherwise, it proceeds to the next step. In this case the condition checks if the
iis 9 or less. - CODE – this is where the code executes, in our case it prints the current value of
i. - INCREMENT – After the
codepart, the INCREMENT part is run, usually incrementing some variables, such asi++. - LOOP AGAIN – Then it goes back to CONDITION and keeps going until CONDITION evaluates as false.
The example code shown above should produce the below result. Try running it!
$ ./ex2
0123456789Conclusion
This everything about loops in C. We will work more carefully with the for loop in the next lesson where we are going to go over C’s arrays and strings.
See you until then! 😁