1 lecture 5 more flow control structures for do continue break switch structured programming ...
Post on 22-Dec-2015
220 views
TRANSCRIPT
1
Lecture 5 More flow control structures
for do continue break switch
Structured programming Common programming errors and tips Readings:
Chapter 3: Section 10-21
2
for statement General form of for-statement
repetition statement
for (expr1; expr2; expr3) statement
The above form is equivalent to the following while statement given that expr2 exists, and that no continue statement exists in statement
expr1;while (expr2) { statement expr3;}
3
Example of for statement
/* To sum 1 to 100 */ #include <stdio.h>
int main(void) { int i, sum = 0; for (i = 1; i <= 100; i++) sum + = i; printf(“%d”, sum); return 0;}
4
Comma operator (,) General form is
expr1, expr2 It has the lowest precedence of all operators in C
and is evaluated from left to right The comma expression as a whole has the value
and type of its right operand Sometimes used in for statements to allow
multiple initializations and multiple processing of indices
The comma operator is rarely used Not all commas in a C program are comma
operators
5
Examples of comma operator
sum=0;
for (j=1; j<=10; j++)
sum += j;
and
for (sum=0,j=1; j<=10; j++)
sum += j;
and
for (sum=0,j=1; j<=10; sum += j, j++)
;
are equivalent
6
do statement General form of do statement (repetition
statement)
do { statement
} while (expression);
Semantics: statement is executed first; thus the loop
body is run at least once If the value of expression is non-zero (true),
the loop repeats; otherwise, the loop terminates
7
Example of do statementint error; /* no Boolean type support */int n;...do {
printf(“Input a positive integer: ”);scanf(“%d”, &n);
if (n <= 0) { error = 1; /* non-zero value */
printf(“\nError: -ve input!\n”}; } else error = 0;} while (error);...
8
Program Remarks The variable error is used as a flag:
When it is non-zero, it indicates that n0 When it is zero, it indicates that n>0 The do-while statement makes use of error to
determine whether to continue or not If we want to execute the loop-body at least
once, it is more convenient to use a do-while statement than a while statement. E.g., compare this loop with that on slide 14 of lecture 4.
While-statements can often be written as for-statements, and vice-versa.
9
break statement the break statement causes an exit from the
innermost enclosing loop or switch statement (discussed later)
while (1) {
scanf(“%lf”, &x);
if (x < 0)
break; /* exit loop if x is -ve */
printf(“%f\n”, sqrt(x));
}
/* If break is run, jumps to here */
10
continue statement
continue statement causes the current iteration of a loop to stop and the next iteration to begin immediately
It can be applied in a while, do-while or for statement
11
Example of continue statement
/* read in and sum 10 not-too-small nos. */
cnt = 0;
while (cnt < 10) {
scanf(“%lf”, &x);
if (x > -0.01 && x < 0.01)
continue; /* discard small values */
++cnt;
sum += x;
/* continue transfer control here */
}
12
switch statement General format of switch statement (selection
statement)
switch (expression) { case constant_expr1: statement_seq1
case constant_expr2: statement_seq2
...
...
case constant_exprN: statement_seqN
default: statement_seq
}
13
switch statement (cont’d) Semantics
Evaluate the switch expression which results in an integer type (int, long, short, char)
Go to the case label having a constant value that matches the value of the switch expression; if a match is not found, go to the default label; if default label does not exist, terminate the switch
Terminate the switch when a break statement is encountered
If there is no break statement, execution “falls through” to the next statement in the succeeding case
14
Example of switch statement
/* To print the no. of days in a month */
scanf(“%d”, &month); /* assume month is integer var.*/
switch(month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
printf(“31 days”);
break;
case 4: case 6: case 9: case 11:
printf(“30 days”);
break;
case 2:
printf(“28 days “);
break;
default:
print(“input error”);
}
15
Another example: switch/* To find out the type of value stored in variable c (a character variable) */switch (c) { case ‘0’: case ‘1’: case ‘2’: case ‘3’: case ‘4’: case ‘5’: case ‘6’: case ‘7’: case ‘8’: case ‘9’: printf(“A digit\n”); /* no braces is needed */ break; case ‘ ’: case ‘\n’: case ‘\t’: printf(“A white-space\n”); break; default: printf(“A letter or special character\n”); break;}
16
Another example
Task: write a program that reads in two integers, month and day; and then calculates the number of days from 1/1/2003 to day/month/2003
Idea: Step 1: Calculate the number of days from
January up to month-1 Step 2: Add day to the number of days
calculated in step 1
17
conditional (?:) operator
General format of ?: operator is
expr1 ? expr2 : expr3
Semantics expr1 is evaluated If the above result is non-zero, then expr2 is evaluated;
else expr3 is evaluated The value of the whole ?: expression is the value of
expression evaluated at the end
18
Structured Programming Structured programming statements are single-entry
and single exit
Structured programming
construct
Goto statements will render some programming constructs to have more than one entry/exit
20
Structured Programming Guidelines
The flow of control of a structured program is easier to follow
How? Apply stepwise refinement to decompose a problem
into smaller problems repeatedly until they are simple enough to be coded
In each refinement, apply one of these 7 control structures: compound, if-, if-else, switch, while, do-while, for
For efficiency purpose, may use continue/break statements with great care
21
Common programming errors
Mix up = and ==E.g. the expression in the following if-statement is always false:
if (x=0) printf(“Hello\n”);
Use == for equality testing: if (x==0)
...
22
Common Programming Errors (cont’d)
Mix up , and ;
E.g. for (j=1, j<=10, j++) /* error */
sum += j;
Put in extra semi-colons, e.g.,
sum=0;
for (j=1; j<=10; j++);
sum += j;
Misuse of relational operators
if (2 < k < 7) // wrong
if (2 < k && k < 7) // correct
23
Some Programming Tips
Make sure that the termination condition of a loop is reachable: If possible, use < > <= >= instead of == !=
Don’t use a variable of any floating point type to control a loop because real numbers are represented in their approximate values internally
Infinite loop can be made deliberately: while (1) statement for (;;) statement