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 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 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 );
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, 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.
To count from 3 to 28, I use ...
for loop.
Try again...
To check if a number is even or odd, I use ...
if is enough.
Try again...
To wait for a sensor to change state, I may use ...
Is the while loop well adapted in the code below?
scanf ("%d", &N);
while ( N<0 ) {
scanf ("%d", &N);
}
do..while loop is a better option.
Try again...