Loops allow you to execute a block of code until the test for a termination condition fails. There are 3 types of loops which you will find useful in C: while, for and do-while.

While loop

While statements allow the programmer to express a decision that is to be made for each iteration:

The expression is first evaluated, and if found to be true (non-zero), the block of statements is executed, then the expression is evaluated again. The cycle will continue until the expression is found to be false (zero).

For loop

This type of loop is more appropriate when the programmer's goal is to count some number of iterations:

<expression1> performs loop initialization, <expression2> is a stopping condition and <expression3> performs loop incrementing.

The above will produce the output:

0 1 2 3 4 5 6 7 8 9

First the expression (i < 10) is evaluated, then in each iteration the printf statement is executed to print the current value of i. After the statement is executed, i is incremented by one (i++) and the cycle continues until i is no longer less than 10.

Do-while loop

Most programmers will only use while and for loops, but the do-while loop provides one additional feature: the loop body is guaranteed to execute at least once.

The do-block is executed first, then the condition is evaluated. When the expression is found to be false (zero) the loop terminates.

©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement