3. Loop Statements
|
|
There are several loop statements: |
– The while loop
– The for loop
– The do-while loop
– The break and continue keywords |
|
3.1 Loops – While and For |
|
3.1.1 while statement |
|
|
– Simplest loop structure – evaluate body as long as condition is true
– Condition evaluated first, so body may never be executed |
|
|
|
3.1.2 for statement |
|
|
– Inside parentheses, three expressions, separated by semicolons: |
Initialization; Condition; Increment |
– Expressions can be empty (condition assumed to be “true”) |
int factorial(int n) |
{ |
int i, j=1;
for (i=1; i<=n; i++) j *= i;
return j; |
}
int factorial(int n)
{ |
int i=1; int j=1;
while (i<=n) { |
j *= i;
i++; |
}
return j; |
}
int factorial(int n) {
{ |
int i, j;
for (i=1, j=1, i<=n; j*=i, i++) ;
return j; |
} |
|
|
|
3.1.3 The do-while Loop |
|
The syntax of the do-while loop is |
|
|
|
Example |
|
|
|
3.2 Break and Continue |
|
The break Keyword |
– Sometimes want to terminate a loop early
– break; exits innermost loop or switch statement to exit early |
|
|
The continue Keyword |
– Use to skip an iteration
– continue; skips rest of innermost loop body, jumping to loop condition |
|
|
|
3.3 Goto and Labels |
|
3.3.1 goto statement |
|
C provides the infinitely-abusable goto statement, and labels to branch to. |
goto allows you to jump unconditionally to arbitrary part of your code (within the same function). |
the location is identified using a label. a label is a named location in the code. It has the same form as a variable followed by a ’:’ |
|
|
Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it [1]. Dijkstra. Go To Statement Considered Harmful. Communications of the ACM 11(3),1968. |
– Excess use of goto creates sphagetti code.
– Using goto makes code harder to read and debug.
– Any code that uses goto can be written without using one. |
|
3.3.2 error handling |
|
Language like C++ and Java provide exception mechanism to recover from errors. In C, goto provides a convenient way to exit from nested blocks. |
|
|
|