Академический Документы
Профессиональный Документы
Культура Документы
Control Flow
Joy Mukherjee
1 / 38
Outline
1 Branching
2 Selection
3 Loop/Iteration
2 / 38
Control Flow
3 / 38
Statements and Blocks
4 / 38
Outline
1 Branching
2 Selection
3 Loop/Iteration
5 / 38
Branching Statements
Based on the result of the logical test, one of several possible actions
will be carried out.
6 / 38
The if Statement
if (Expression) {
Block 1
}
block means a sequence of statements. If the block consists of a
single statement, the braces may be omitted.
Suppose you scan an integer x from the user and then replace it with its
absolute value. if x is greater than or equal to 0, there is nothing to do. If
x is negative, replace it by -x.
scanf(%d,&x);
if (x < 0)
x = -x;
7 / 38
The if-else Statement
if (Expression) {
Block 1
} else {
Block 2
}
Suppose you scan an integer x from the user and assign to y the absolute
value of x. if x is bigger than or equal to 0, then simply copy x to y. If x is
negative, copy -x to y.
scanf(%d,&x);
if (x >= 0)
y = x;
else
y = -x;
8 / 38
Nested if Statements
A block of an if or if-else statement may itself contain one or more if
and/or if-else statements. Suppose that we want to compute the absolute
value |xy | of the product of two integers x and y and store the value in z.
Here is a possible way of doing it:
if (x >= 0) {
z = x;
if (y >= 0)
z *= y;
else
z *= -y;
} else {
z = -x;
if (y >= 0)
z *= y;
else
z *= -y;
}
9 / 38
The if-else Statements
if (x >= 0)
z = x;
else
z = -x;
if (y >= 0)
z *= y;
else
z *= -y;
10 / 38
The if-else Statements
if ( ((x >= 0) && (y >= 0)) || ((x < 0) && (y < 0)) )
z = x * y;
else
z = -x * y;
11 / 38
Confusion: Nested-if
Because the else part of an if-else is optional,there is an ambiguity when
an else if omitted from a nested if sequence. This is resolved by
associating the else with the closest previous else-less if. For example,
if (n > 0)
if (a > b)
z = a;
else
z = b;
the else goes to the inner if, as we have shown by indentation. If that isnt
what you want, braces must be used to force the proper association:
if (n > 0) {
if (a > b)
z = a;
}
else
z = b;
12 / 38
Multi-way Branching
if (Expression 1) {
Block 1
} else if (Expression 2) {
Block 2
} else if (. . .)
...
} else {
Block n
}
The last else part handles the none of the above or default case where
none of the other conditions is satisfied. Sometimes there is no explicit
action for the default; in that case the trailing
else {
Block n
}
can be omitted, or it may be used for error checking to catch an
impossible condition.
13 / 38
Multiway Branching
14 / 38
Outline
1 Branching
2 Selection
3 Loop/Iteration
15 / 38
Selection Statements
16 / 38
The switch-case-default Statement
The switch statement is a multi-way decision that tests whether an
expression matches one of a number of constant integer values, and
branches accordingly.
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
Each case is labeled by one or more integer-valued constants or
constant expressions.
If a case matches the expression value, execution starts at that case.
All case expressions must be different.
The case labeled default is executed if none of the other cases are
satisfied.
A default is optional; if it isnt there and if none of the cases match,
no action at all takes place.
Cases and the default clause can occur in any order.
17 / 38
The switch-case-break-default Statement
Condition i stands for (E == vali ), where E is an expression and vali are
possible values of the expression for i = 1, 2, . . . , n. One can write this as:
switch (E) {
case val1 :
Block 1
break;
case val2 :
Block 2
break;
...
case valn :
Block n
break;
default:
Block n+1
}
18 / 38
Example
19 / 38
Strange Behavior of switch Statement
The switch statement has a strange behavior that necessitates the use
of the break statements.
It keeps on checking if the value of the top expression matches the
case values. Once a match is found, further comparisons are disabled
and all following statements before the closing brace are executed one
by one.
Avoid this difficulty by putting additional break statements as and
when required. This statement causes the program to leave the
switch area without proceeding further down the area.
20 / 38
Example
Suppose you want to compute the sum n + (n+1) + ... + 5 for n in the
range 0 <= n <= 5. For other values of n, an error message need be
printed. The following snippet does this.
sum = 0;
switch (n) {
case 0 :
case 1 : sum += 1;
case 2 : sum += 2;
case 3 : sum += 3;
case 4 : sum += 4;
case 5 : sum += 5;
break;
default : printf(n = %d is not in the desired range.\n, n);
}
21 / 38
Outline
1 Branching
2 Selection
3 Loop/Iteration
22 / 38
Loop/Iteration Statements
23 / 38
The while Loop
while (expression) {
Block1
}
24 / 38
GCD using while Loop
The algorithm calculates the gcd of two integers, first and second, where
first > second.
while (second > 0) {
remainder = first % second; /* Compute the next remainder */
first = second; /* Replace first integer by second integer */
second = remainder; /* Replace second integer by remainder */
}
printf(gcd = %d\n, first);
25 / 38
The for Loop
26 / 38
Common Form: The for Loop
27 / 38
1
Harmonic Number Hn = 1 + 21 + . . . + 1
n
float H = 0.0F;
for (i=1; i <= n; ++i)
H += 1.0 / i;
printf(H(%d) = %f\n, n, H);
28 / 38
Reverse a String
#include <string.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i < j; i++, j - -) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
29 / 38
The n-th Fibonacci Number
30 / 38
The do-while Loop
The do-while loop tests the termination condition at the bottom after
making each pass through the loop body; the body is always executed at
least once. The syntax of the do-while loop is as follows.
do {
Block 1
} while (expression); /* Note the ; at the end */
31 / 38
Display Integers from 0 through 9
#include stdio.h
int main()
{
int digit = 0;
do {
printf(%d\n, digit++);
} while (digit <= 9);
return 0;
}
32 / 38
Outline
1 Branching
2 Selection
3 Loop/Iteration
33 / 38
Unconditional Jump Statements
return
break
continue
goto
Use
You can use return and goto anywhere inside a function.
You can use the break and continue statements in conjunction with
switch statement
You can use the break and continue statements in conjunction with
any of the loop statements (while, for, do-while).
34 / 38
The return Statement
return expression;
35 / 38
The break Statement
Exit from a loop other than by testing at the top or bottom.
The break statement provides an early exit from for, while, and
do-while loop, just as from switch.
A break causes the innermost enclosing loop or switch to be exited
immediately.
The following function removes trailing blanks, tabs and newlines from the
end of a string.
#include < string.h >
int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n=n-1)
if (s[n] != && s[n] != \t && s[n] != \n)
break;
s[n+1] = \0;
return n;
} 36 / 38
The continue Statement
The continue statement forces the next iteration of the enclosing for,
while, or do-while loop to take place ignoring the remaining part of
the loop body for the current iteration.
For the for loop, continue causes the increment and then the
conditional test portions of the loop to execute.
For the while and do-while loops, program control passes to the
conditional tests.
The program sums up only the non-negative elements in the array a;
negative values are skipped.
for (i = 0; i < n; i++) {
if (a[i] < 0) /* skip negative elements */
continue;
sum = sum + a[i];
}
37 / 38
The goto Statement
Makes programs unreadable and difficult to debug.
Use: Breaking out of two or more loops at once.
The goto statement requires a label for operation.
A label is a valid identifier followed by a colon that can be used either
before or after goto.
Label must be in the same function as the goto that uses it - you
cannot jump between functions.
for ( . . . ){
for ( . . . ) {
...
if (disaster)
goto error;
}
...
}
error:
/* error handling actions */ 38 / 38