Loops
While loop
while (expr) {
statements;
}
- Braces are optional (for a single
statement).
Do ... while
do {
statements;
} while (expr);
- Braces are optional (for a single
statement).
For loop
for (initial-expr; cond-expr; incr-expr) {
statements;
}
- initial-expr : Evaluated once before the
loop is executed.
- cond-expr : Evaluated before each
iteration of the loop; if
the value is false, the execution of the loop stops immediately.
- loop-expr : Evaluated at the end of each
iteration of the
loop, or after a "continue" statement is encountered.
- Braces are optional (for a single
statement).
Jump statements
- break : Break from the loop immediately.
- continue : Continue on to the next
iteration of the loop.
- goto <label>: Jump to the specified
label.
- "goto" statements are sometimes used to
break out of nested
loops.
- Avoid using "goto" statements whenever
possible as they generally cause
the code to be less readable and maintainable.
Examples
int sum = 0;
int i = 1;
while (i < 10) {
if (i == 3) {
continue; /* Skip the rest of this loop iteration. */
}
sum += i;
if (sum > 15) {
break; /* Exit the loop. */
}
}
goto LABEL1;
LABEL2:
goto LABEL3;
LABEL1:
goto LABEL2;
LABEL3: