Lesson 6.4. How to choose the right loop in C ?

There are three loops in C: for, while and do..while. Each loop has particularities that make it more or less suitable to a given task. The 3 loops are interchageable, but the resulting code may be less readable, or even less efficient. Experienced developers have developed habits that have become a kind of informal standard. This is what we call best practices. The example below shows three programs that count from 0 to 100 by ten:

i=0;  
while (i<=100) {
  printf ("%d ", i);
  i += 10;
}
i=0;
do { 
  printf ("%d ", i); 
  i += 10;
}
while (i<=100);
printf ("\nBoucle for :\t\t");
for ( i=0 ; i<=100 ; i+=10 )
  printf ("%d ", i); 

The for loop is clearly the most user-friendly, but also the most concise.

The for loop

The first question to ask when choosing a loop is whether the for loop is the most suitable. If the answer to the following questions is yes, then most likely the for loop is what you need:

In other words, if you know where and how far you are counting, as well as the counting step: no hesitation it is a for loop that you should use.

The do..while loop

The special feature of the do..while loop is that it always executes the block of instructions at least once. If the for loop is not appropriate, and you always execute the body of the loop at least once, use a do..while loop.

For example, the do..while loop is used in embedded systems to wait for the triggering of an event. This is called event-polling:

\\ Waits for the button to be pressed
do { 
  buttonPressed = readButton(); 
} while ( !buttonPressed );

The while loop

Finally, if the for and do..while loops are not suitable, the best option is undoubtedly the while loop. Here is an example of code that waits for the user to press a key (kbhit = KeyBoard HIT) :

// Waits for a key press on the keyboard
while ( !kbhit() );

In summary

In summary, when you know where you start and stop counting, the best option is usually a for loop.

Otherwise, if the instruction block habe to be executed at least once, used a do..while loop, otherwise use a while loop.

Quiz

To count from 3 to 28, I use ...

Check Bravo! We know where the loop will start and stop, we use a for loop. Try again...

To check if a number is even or odd, I use ...

Check Bravo! No need for a loop, an if is enough. Try again...

To wait for a sensor to change state, I may use ...

Check Bravo! It depends on whether the sensor is to be read in the loop body or not. Try again...

Is the while loop well adapted in the code below?

scanf ("%d", &N);
while ( N<0 ) {
    scanf ("%d", &N);
}
Check Bravo! The block is necessarily executed once. A do..while loop is a better option. Try again...

See also


Last update : 11/19/2022