Skip to main content
Engineering LibreTexts

7.3: Looping

  • Page ID
    35831
  • There are three looping constructs in C. They are while(), do-while(), and for(). do-while() is really just a while() with the loop continuation test at the end instead of the beginning. Therefore, you always get at least one iteration. The continuation test follows the same rules as the if() construct. Here are the while() and do-while() templates:

    while( test condition(s)... )
    {
        //...statements to iterate...
    }
    
    do {
        //..statements to iterate...
    } while( test condition(s)... )
    

    Here are some examples:

    while( a<10 )
    {
        /* Perhaps a is incremented in here.
           If a starts off at 10 or more, this loop never executes */
    }
    
    do {
        /* Perhaps a is incremented in here.
           If a starts off at 10 or more, this loop executes once */
    } while( a<10 )
    
    while( a<10 && b )
    {
        /* This loop continues until a is 10 or more, or b is zero.
           Either condition will halt the loop. Variable a must be
           less than 10 and b must be non-zero for the loop to
           continue */
    }
    

    Usually, loops use some form of counter. The obvious way to implement a counter is with a statement like:

    a=a+1;    /* add one to the current value of a */
    

    C has increment and decrement operators, ++ and --, so you can say things like:

    a++;    /* add one to the current value of a */
    a--;    /* subtract one from the current value of a */
    

    C also has a shortcut mode for most operations. Here are two examples:

    a+=1; /* equivalent to a=a+1; or a++; */
    a*=2; /* equivalent to a=a*2; */
    

    You will see all three forms of increment in example and production code, although the increment and decrement operators are generally preferred.

    The for() construct is generally preferred over the while() if a specific number of iterations are known. The template is:

    for( initialization(s); termination test(s); increment(s) )
    {
        ..statements to iterate..
    }
    

    Here is an example using the variable a as a counter that starts at 0 and proceeds to 9 by adding one each time. The loop iterates 10 times.

    for( a=0; a<10; a++ ) {
        /* stuff to do ten times */
    }
    

    The following example is similar, but adds 2 at each loop, thus iterating 5 times.

    for( a=0; a<10; a+=2 )
    {
        /* stuff to do five times */
    }
    

    The next example uses multiples. Note the use of commas.

    for( a=0, b=1; a<10; a++, b*=3 )
    {
        /* stuff to do ten times */
    }
    

    In this case two variables are initialized. Also, at each loop completion, a is incremented by 1 and b is multiplied by 3. Note that b is not used in the termination section, although it could be.

    If the iterated block within the braces consists of only a single statement, the braces may be left out (just like in the if/else construct). Loops may be nested and contain any legal C statements including assignments, conditionals, function calls and the like. They may also be terminated early through the use of the break statement. As in the switch/case construct, the break command redirects program flow to the closing brace. Here is an example:

    for( a=0, b=2; a<7; a++ )
    {
        while( b<a*10 )
            b*=2;
    
        if( b > 50 )
            break;
    }
    

    Note that the if() is not part of the while(). This is visually reinforced by the use of indents and spacing, but that’s not what makes it so. The code would behave the same even if it was entered like so:

    for( a=0, b=2; a<7; a++ ){ while( b<a*10 ) b*=2; if( b>50 ) break;}
    

    Obviously, the former style is much easier to read than the later. It is strongly recommended that you follow the first style when you write code.

    OK, what does the code fragment do? First, it sets a to 0 and b to 2. Then, the while() checks to see if b is less than 10 times a. 2 is not less than 0, so the while() doesn’t iterate. Next, the if() checks to see if b is more than 50. It’s not, so the break isn’t executed. That concludes the first iteration. For the second iteration, a is incremented to 1 and checked to see if it’s still less than 7. It is, so the loop continues and enters the while(). b is smaller than 10 times a (2<10), so b is doubled to 4. This is still smaller so it’s doubled again to 4, and again to 8. Finally, it is doubled to 16. It is now larger than 10 times a so the while() loop exits. The if() isn’t true as 16 is not larger than 50 so the break isn’t taken. We wind up finishing iteration two by incrementing a to 2. The while() loop starts because b (16) is less than 10 times a (now 20). The loop will only execute once, leaving b at 32. This is still less than 50, so the break is ignored. The for() closes by incrementing a to 3. On the next iteration both the while() and if() are ignored as b is less than 10 times a as well less than 50. All that happens as that a is incremented to 4. Now that a is 4, the while() starts again (32<40). b is doubled to 64. That’s greater than 10 times a, so the while() exits. b is now greater than 50 so the if() is taken. This results in executing the break statement that directs program flow to the closing brace of the for() loop. Execution picks up at the line following the closing brace and we are all done with the for() loop (no, a never gets to 7). This example is admittedly a little tricky to follow and not necessarily the best coding practice, but it does illustrate how the various parts operate.