C Language

To share this page click on the buttons below;

Loops

Loops are present in every programming language. You need ‘to loop‘ your code when you want a part of your code being executed more than once. For example suppose that you want to initialize all the element of an array with hundreds of element to different values: the simplest and effective solution is to use a loop. That is a simple example, but within a loop you can, of course, put whatever code you want.

C language supports three different kind of loop:

  • while loop
  • for loop
  • do, while loop

while loop

The while loop can be defined this way:


while(<condition>) {
   /* code executed until the <condition> is true */
}

You use the reserved word while followed by round brackets, within this brackets you put the condition of the loop: that means that until (while) the condition is true (remember false is 0, true is everything else) all the code contained in the following braces will be repeatedly executed. Each time the code is executed is an iteration of the code, before the execution of an iteration the condition is checked, if it is still true then a new iteration is performed otherwise the code execution jumps at the first statement following the ending brace of the while loop. Unless you want your loop to be executed forever there must be within the iteration is something that is able to change the from true to false.

As usually a little example would probably worth more than thousand words:

#include <stdio.h>

/* program to demonstrate while loop */

void main(void) {

    int array[10];

    int i = 0;
    /* that will initialize the elements of array 
       from 1 to 10 */
    while(i < 10) {
        array[i] = i + 1;
        i = i + 1;
    }

    /* reset the condition of the while */
    i = 0;
    /* that will print the content of the array */
    while(i < 10) {
        printf("array[%d] = %d\n", i, array[i]);
        i = i+1;
    }

    printf("Program finished... bye\n");
}

You see something that is somehow typical, the condition that i is lower than 10 is checked in the while and then i is incremented by one (i = i + 1) within the loop body, that allows the while reaching the exit condition.

Additionally please note that first the condition is checked and then the loop body executed: if the condition is already false the loop body is never executed.

for loop

The syntax of the for loop is just a little bit more complex:

/* first the <initialization> is performed */
for( <initialization> ; <condition>; <increment> ) {

   /* the code here is executed untill 
      <condition> is true*/ 

   /* the <increment> is automatically executed
      at the end of each iteration */
}

The for loop is identified by the reserved word for: immediately after that there are round brackets and after that a pair of braces, just like the while loop. Within the braces there is the body of the loop (i.e. the the code that will be repeatedly executed). The important difference respect to the while loop is what is contained within the round brackets.

Within the round brackets there are three different statements:

  • the initialization is performed just once at the beginning of the loop
  • then the condition is checked, if true the body of the loop is executed otherwise the execution jumps to the next statement after the loop
  • if the body of the loop is executed then at end of each iteration the increment is automatically executed.

At the beginning and before of each new iteration the condition is checked again. These three statements are separated by a semicolon.

The following example works exactly in the same way than the previous one but it uses the for loop instead of the while one:

#include <stdio.h>

/* program to demonstrate while loop */

void main(void) {

    int array[10];

    int i = 0;
    /* that will initialize the elements of array 
       from 1 to 10 */
    for(i = 0; i < 10; i = i + 1) {
        array[i] = i + 1;
    }

    /* that will print the content of the array */
    for(i = 0; i < 10; i = i + 1) {
        printf("array[%d] = %d\n", i, array[i]);
    }

    printf("Program finished... bye\n");
}

What you see in the example above is what is somehow typical for a for loop: the initialization is used to set a variable to a certain value, the condition checks when the value of the variable exceeds some threshold and the increment changes the value of the variable at the end of each iteration.

These three statements however can be different and can perform different actions depending upon your needs. Sometimes for example it is necessary to initialize and increment 2 variables instead of one: that can be done by separating that operations by a commas like this:

for( a = 0, b = 1 ; b < 24; a = a - 1, b = b + 3 ) {
   /* body of the loop */ 
}

Although that is possible (along with different and more complex syntax) I discourage the use of this possibility because the code become more difficult to be understood.

do,while loop

The do,while loop is very similar to the while except for one thing: the loop iteration (the body of the loop) is always executed at least once, then the condition is checked and if true a new iteration will begin. The syntax is very simple and uses the reserved words do and while:

do {
  /* loop iteration */
} while( <condition> )

n see the condition now is at the end of the loop, so it will be checked after the loop iteration and that ensure that the loop body is executed at least once.

for vs. while

I think that the difference between the while loop and the do, while is pretty self-evident, but you might wonder if there are rules or best practices to choose between the for and the while loop. Well the short answer is no. You can achieve the same result using either the for or the while loop, but the presence of these two different tools gives you some more flexibility. Although that is hard to explain you will soon recognize, with experience, that sometimes one is "better" than the other. Here are just a couple of hints to reflect upon.

The for loop is certainly more suitable when you know in advance how many iterations you need to do. For example you are "looping" over all the elements of an array (to look for something or perform calculus on each element). The while loop on the other hand, might be more appropriate when you do not know when you will exit from the loop because you are waiting for something to happen: a good example can be receiving data from somewhere.

Perhaps that is the semantic difference between the two loops (but this is just my personal feeling): the while loop is somehow associated with concept of waiting until a condition is reached, while the for loop is somehow associate with the concept to "iterate" over something (typically a collection of data, or something like that).

Exit in advance

We have seen that the condition check allows the exit from the loop, but sometime you want to exit in advance. For example suppose that you are looking for a value into an array, you just want to check if that value is present or not: it makes no sense when you find it to continue until the end of the array.

In cases like these you can use the break statement, that we already met in the case of the switch, case statement.

When a loop meets a break inside its body, the loop is "broken" and the execution will jump to the next statement after the loop.

The following code shows an example of the break use inside a for loop:

#include <stdio.h>

/* program to demonstrate while loop */

void main(void) {

    int array[10];

    int i = 0;
    /* that will initialize the elements of array 
       from 1 to 10 */
    for(i = 0; i < 10; i = i + 1) {
        array[i] = i + 1;
    }

    /* that will for the value 5 in the array */
    for(i = 0; i < 10; i = i + 1) {
        if(array[i] == 5) {
            printf("Found!\n");
            break;
        }
    }

    /* see that i has not been incremented since the
       break was met */
    printf("The value 5 was found in position %d\n", i);

    printf("Program finished... bye\n");
}

You can use the break statement in all three different C loops. Obviously skipping the iterations that are no more useful is a good practice because that makes programs faster.

Pay attention to the fact that you can "neste" a loop within another loop, if you put the break inside the inner one that will allow you to exit only from that loop and not also from the outer one.

Skipping an iteration

Sometime the code contained into a loop body might contains something that you do not want to be always executed, you want to skip some iterations based upon a certain condition. It may happen in fact that in the middle of the body loop you realize that you do not need to perform all the remaining part of iteration code, but you want just to jump to the next iteration. In other words you do not want to stop the loop execution, but just skips some iterations of the loop body.

That might be achieved using the reserved word continue: when the execution reaches that statement, the remaining part of the body loop is skipped and the execution continues from the next iteration (before, of course, the condition to remain in the loop in always checked).

That example shows the use of continue to skip the division by 0:

#include <stdio.h>

/* program to demonstrate while loop */

void main(void) {

    int array[10];

    int i = 0;
    /* that will initialize the elements of array 
       from 1 to 10 */
    for(i = 0; i < 10; i = i + 1) {
        array[i] = i + 1;
    }

    /* on of the element of the array is set to zero */
    array[5] = 0;

    /* we will use all the element of the array to
       perform a division  */
    for(i = 0; i < 10; i = i + 1) {
        if(array[i] == 0) {
            /* we cannot divide by 0! but we want
               continue with other valid values */
            continue;
        }
        else {
            print("100 / %d = %d\n", array[i], 100 / array[i]);
        }    
    }

    printf("Program finished... bye\n");
}

Looping forever

What happens if you put into a loop condition something that is always true? Well, simply the body loop will be executed forever.

That seems something to be avoided and the truth is that very often that is a bug in your code (for example you forgot to change the variable value that trigger the loop stop into a while loop), but this is not always true. Sometimes looping forever is just what you really want to do.

Perhaps that is more common in embedded programming (an embedded program is what controls any electronic devices, like your dishwasher or you mp3 player), but sometimes you just want your program being executed over and over just waiting for something to happen (perhaps the user open the dishwasher or presses the play button). In these cases you will find something like:

while(1) {

   /* your program code will be executed 
      forever */

}

Or also:

for(;;) {

   /* your program code will be executed 
      forever */

}

Obviously you can always exit from and infinite loop using the break statement.

Best practices

We have seen that the break statement allows you to exit in advance from a loop: we can say that the use of break is a sort hidden exit door. While, in fact, the condition to exit from the loop is always explicitly declare in the loop statement, the break might be somewhere in your body loop and can be difficult to see, especially when the body of the loop is big with many lines of code.

That reduces the readability of the code, because forces the reader to search through the body loop code for other conditions (different from the "main" of the loop) that may cause the loop to stop. Suppose that someone has to make changes or performs maintenance of the code: it is "polite" and useful that all the conditions to exit from the loop are immediately recognizable without any further search.

In these cases I will suggest 2 possible strategies: the first one is to comment your code, listing for the additional conditions that may cause the end of the loop execution, the second one is to use an additional variable, something that is usually called a flag, and avoid the use of break: you set that variable to a value that trigger the exit from the loop (instead to use the break) and you explicit use that variable in the "main" condition of the loop.

To share this page click on the buttons below;