Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Looping

Almost every useful program requires loops and tests, which determine how the program will proceed. Without this feature, a program might as well be a text file, which generates its contents on every execute.

There are three basic loops which we generally recognize.

The for loop sets an initial condition when we enter the loop, then performs a test at the beginning of every iteration, and (if the test is still TRUE), performs a special action at the end of the iteration. We use this to perform a large repetition where the condition is fairly simple (e.g. repeat this action 10 times).

The while loop performs a test at the beginning of every iteration. If the test is TRUE, the block of code below it executes; if the test is FALSE, the program jumps past the block of code below.

The do-while loop acts like a while loop, but it performs the test at the END of the code block. This means that the code will always execute at least once.

Finally, the if test is essentially a loop which performs the test and executes its code block only once.


Generate this program in vi (as we learned previously), and call the source file loop.c.

#include <stdio.h>

This code increments the value "iterator" in three different ways. All three are useful in their own ways.
int main(int argc, char *argv[])

//Define a number (int) which we will call "iterator"
int iterator;

//Initial condition: iterator = 0
//Test: Is iterator < 10?
//Iteration: iterator increments by 1
for (iterator = 0; iterator < 10; iterator++)
printf("FOR LOOP: %dn", iterator);

//Test: is iterator < 15?
while(iterator < 15)
printf("WHILE LOOP: %dn", iterator-10);
//iterator is equal to itself plus 1
iterator += 1;

//Test: is iterator < 15?
//Note: we know for a fact that it will be false.
printf("DO-WHILE LOOP: %d\n", iterator -15);
iterator = iterator +1;
while(iterator < 15);

//Test: is iterator greater than or equal to 15?
//We know for a fact it will be true.
if(iterator >= 15)
printf("Iterator = %d\n", iterator);
//If this code executes, it means the if was false. How can that be?
printf("How did I get here?\n");

printf("END OF PROGRAM! GOOD DAY!\n\n");
return 0;

You can compile and run this code using gcc. For example, you can run the following in the terminal:

gcc -o loop loop.c


Look closely at the output. Does it look like you would expect?

Play with it

Compile the same program, but change the tests and/or the iterators. You’ll be using these loops quite a bit, so it’s important to fully understand how they work.