While
We have already encountered while loop.
while (expression) statement
If the expression results in a non-zero value, statement is executed and the expression gets re-evaluated. This cycle continues until expression yields zero.
Do-while
In contrast with a while loop, a do-while loop checks the condition at the end of the loop, meaning that the loop body gets executed at least once.
do statement while (expression);
The statement is executed, then the expression get evaluated. If it is true (non-zero value), then the statements gets executed again, followed by expression evaluation. Again, this continues until the expression yields false (zero value).
Here is a function to reverse an integer using do-while:
int reverse(int num) { int rev = 0; int coeff = 1; if (num < 0) { coeff = -1; num = num * -1; } do { rev = rev * 10 + num % 10; } while ((num /= 10) > 0); return coeff * rev; }
For
The for loop
for (expr1; expr2; expr3) statement
is equivalent to
expr1; while (expr2) { statement expr3; }
Although all the three components of a for loop are expressions, usually expr1 and expr3 are assignments or function calls, whereas expr2 is a relational expression. All the components in a for loop are optional, though the semicolons are mandatory.
for (;;) { ... }
results in an infinite loop (could be broken by break or return).
Although the choice of which loop to use is personal, the for loop is preferable when there is a simple initialisation and increment, since it keeps the loop control statements visible and close together at the top of the loop. Example:
for (i = 0; i < n; i++) ...