← Old blog

25 Oct 2020 · C language · How to C

How to C for beginners, part 5 loops

Written when I was a student and restored as it was. Archived original

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)

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:

The example code shown above should produce the below result. Try running it!

$ ./ex2
0123456789

Conclusion

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! 😁

wecros.com