60-140 lecture 3 dr. robert d. kent program control - details
TRANSCRIPT
![Page 1: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/1.jpg)
60-140 Lecture 3
Dr. Robert D. Kent
Program Control - Details
![Page 2: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/2.jpg)
Lecture 3: OutlineProgram control
Generalities versus detailsDecision control
Nested if-else control structuresThe switch control structure
Repetition controlNested while and do-while control structuresThe for control structure
The role of functions in Top-Down design Impact on formulation of well-defined control
structures
![Page 3: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/3.jpg)
3A : Program control
Generalities versus Details
![Page 4: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/4.jpg)
Generalities versus DetailsPreviously, we introduced the basic C control
structuresDecision (Selection)
if if-else switchRepetition
while do-while for
We shall now take another look, in more detailUsage and patternsFlexibility
![Page 5: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/5.jpg)
Generalities versus DetailsUsage and patterns
How are the control structures used in simple, versus complicated, programming circumstances?
What patterns emerge often?These can be re-used
FlexibilityHow flexible is the syntax and grammar of the
control structures?Efficiency versus Clarity
![Page 6: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/6.jpg)
3B. Decision Control
Nested if-else and Switch
![Page 7: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/7.jpg)
3b: OutlineReviewNested if-else control structuresThe switch control structure
![Page 8: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/8.jpg)
ReviewWe have introduced the structured control
mechanisms for decision and selection
Decision:
if ( condition ) Statement ;
Either – perform the Statement (simple or compound) or NOT !Straightforward in most cases
![Page 9: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/9.jpg)
ReviewIf Statement is compound, use braces and
indentation
if ( condition ) { Statement1 ; ...... StatementN ; }
Indentation improves the readability (hence, understanding) of the code for humans.
![Page 10: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/10.jpg)
ReviewSelection:
if ( condition ) T_statement ; /* do when cond is True */ else F_statement ; /* do when cond is False */
Once again, if using compound statements, or if placing a simple statement on a following line, use indentation to improve code readability.This is an either-or situation – perform EITHER the
True clause OR the False clause, but not both!
Many styles exist – use one style consistently in program code.
If ( condition ) { T_stmts ;} else { F_stmts ;}
![Page 11: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/11.jpg)
ReviewSimple Selection:
( condition ) ? T_statement : F_statement
This simple selection structure uses the ternary operator ?: This form may be used as a single control
structure/statementIt is most often incorporated into another statement (eg.
printf) as a component (nested) sub-structure.
If Value is 60, output is: Answer is A
printf( “Answer is %c\n”, (Value > 50) ? ‘A’ : ‘B’ ) ;
![Page 12: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/12.jpg)
Multiple selection – A simple sortProblem:
Enter three integer values and output them in the order from largest to smallestAll values inputted are distinctNote – there are six (6) separate cases to account for
This is called sorting Later we will discuss this for an arbitrary number of
values
![Page 13: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/13.jpg)
Multiple selection – A simple sortSolution:
int A, B, C ;
scanf( “%d%d%d”, &A, &B, &C ) ;
if ( A > B && B > C ) printf( “%d %d %d\n”, A, B, C ) ; if ( A > C && C > B ) printf( “%d %d %d\n”, A, C, B ) ; if ( B > A && A > C ) printf( “%d %d %d\n”, B, A, C ) ; if ( B > C && C > A ) printf( “%d %d %d\n”, B, C, A ) ; if ( C > A && A > B ) printf( “%d %d %d\n”, C, A, B ) ; if ( C > B && B > A ) printf( “%d %d %d\n”, C, B, A ) ;
Note the number of distinct operationsCan this be improved upon (made more efficient)?
CPU instructions are binary for relational comparisons and logic operations. Thus, an expression like:
A > B && B > C
requires three (3) separate operations, namely:
Temp1 = A>BTemp2 = B>CExprvalue = Temp1 && Temp2
3 x 6 = 18
![Page 14: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/14.jpg)
Multiple selection – A simple sortImproved Solution:
if ( A > B ) if ( B > C ) printf( “%d %d %d\n”, A, B, C ) ; else if ( A > C ) printf( “%d %d %d\n”, A, C, B ) ; else printf( “%d %d %d\n”, C, A, B ) ; else if ( A > C ) printf( “%d %d %d\n”, B, A, C ) ; else if ( B > C ) printf( “%d %d %d\n”, B, C, A ) ; else printf( “%d %d %d\n”, C, B, A ) ;
Note the number of distinct operationsCan this be improved upon (made more efficient)? NO !
A minimum of 2 – a maximum of 3!Divide and Conquer (binary subdivision) strategy.
![Page 15: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/15.jpg)
Multiple selectionMultiple selection logic arises when a choice
between more than two possible outcomes may happen
C provides two control structures to deal with these situations if-else (with nesting) switch
![Page 16: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/16.jpg)
Multiple selection Problem:
Part of a calculator program requires the user to input a value from 1 to 4 indicating his/her choice of the operation to perform on two values A and B (assume A, B already entered) RESULT: C = A operation B ;
The interpretation of the inputs is defined as1 - Add2 - Subtract3 - Multiply4 - Divide
![Page 17: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/17.jpg)
Multiple selection : if-elseSolution using if-else :
printf ( “Enter operation code >” ) ; scanf ( “%d”, &Code ) ; if ( Code == 1 ) C = A + B ; else if ( Code == 2 ) C = A – B ; else if ( Code == 3 ) C = A * B ; else C = A / B ;
![Page 18: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/18.jpg)
Multiple selection : switchSolution using switch :
printf ( “Enter operation code >” ) ; scanf ( “%d”, &Code ) ; switch ( Code ) { case 1 : C = A + B ; break ; case 2 : C = A – B ; break ; case 3 : C = A * B ; break ; case 4 : C = A / B ; break ; default : printf ( “Error in input\n” ) ; break ; }
![Page 19: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/19.jpg)
Multiple selection : switchProblem:
Count the number of times that the ‘A’ (or ‘a’) or ‘B’ (or ‘b’) key is pressed, and all remaining alphabetic character keystrokes.
Solution considerations:Need counters for A-keystrokes, B-keystrokes and all
other alphabetic keystrokes.Must ignore non-alphabetic keystrokes such as digits
and punctuation and control signals (eg. ‘\n’) We must differentiate between the alphabetic characters that are
not (‘a’, ‘A’, ‘b’, ‘B’), but which must be counted, and the non-alphabetic keystrokes that are not counted
Recall that the ASCII character code treats the lower case and upper case alphabetic character sequences as ordinal sequences:
‘a’ < ‘b’ < ... < ‘z’ ‘A’ < ‘B’ < ... < ‘Z’
![Page 20: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/20.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
![Page 21: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/21.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
getchar() is a function from <stdio.h> that obtains one character from stdin. In this scenario, the character inputted is assigned to Ch variable.
The value of the condition is the same as the value of Ch.
![Page 22: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/22.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
Use of break implies that the switch must be immediately exited.
![Page 23: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/23.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
Logic Patterns!- reused
![Page 24: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/24.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
Note that break is not required for each case clause. Lack of a break implies that the next case must be processed.
In this case, if Ch is assigned ‘a’, the first case ‘a’ is compared and found to match, but since there is no specific statement to execute, the
processing logic advances to the next case clause (‘A’) and performs the statement: Acnt++ ;
![Page 25: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/25.jpg)
Multiple selection : switch int Acnt = 0, Bcnt = 0, Alphacnt = 0 ;
char Ch ;
switch( Ch = getchar() ) { case ‘a’ : /* lower case */ case ‘A’ : /* upper case */ Acnt++ ; break ; case ‘b’ : /* lower case */ case ‘B’ : /* upper case */ Bcnt++ ; break ; default : if ( (Ch > ‘b’ && Ch <= ‘z’) || (Ch > ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
The default clause is used to handle all other cases that are not explicitly coded. It is possible that this clause may involve complicated logic and processing steps.
Recall that the ASCII character code treats the lower case and upper case alphabetic character sequences as ordinal sequences:
‘a’ < ‘b’ < ... < ‘z’ ‘A’ < ‘B’ < ... < ‘Z’
If Ch is alphabetic and not ‘a’, ‘b’, ‘A’ or ‘B’, then it must lie within one OR the other range of characters.
![Page 26: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/26.jpg)
Multiple selection : switchIt is possible to nest multiple statements and control
structures within each case clause of the switch structureUsually this leads to coding that is difficult to understandTypically, it is advised to keep the logic of each case
clause relatively simple and directLater, we will see that complicated logic is best
encapsulated within C functions (library or user-defined) and these functions can be called (referenced/invoked) within the case clauses.
![Page 27: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/27.jpg)
3C. Repetition Control
While, Do-while and For
![Page 28: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/28.jpg)
3c: OutlineReviewNested while and do-while control structuresThe for control structure
![Page 29: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/29.jpg)
3c. RepetitionRepetition logic may be of two forms
Pre-condition testing : enter, or re-enter, the loop body if the condition is true.
Post-condition testing : enter the loop body in all cases (performing the body a minimum of once), then repeat the loop body only if the condition is true.
C supports three forms of repetition control structures whiledo-while for
![Page 30: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/30.jpg)
Repetition : while while ( condition_expression )
statement ;
while ( condition_expression ) { statement1 ; ...... statementN ; }
cond
process
FALSE
TRUE
![Page 31: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/31.jpg)
Repetition : do-while do
statement ; while ( condition_expression ) ;
do { statement1 ; ...... statementN ; } while ( condition_expression ) ;
MUST execute the body (process) at least once!
cond
process
FALSE
TRUE
![Page 32: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/32.jpg)
Repetition : NestingConsider a do-while that contains another do-
while structure:
cond
FALSE
TRUE
cond
process
FALSE
TRUE
Nested do-while loop.
![Page 33: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/33.jpg)
Repetition : NestingNesting of control structures within other control
structures occurs quite often in programmingLoop structures require care in order to ensure that
all control conditions are properly establishedAlways remember to check that any statements that
must be performed outside the formal control structure (eg. initializations) are strongly coupled to the structure.
Inner loop structures may reference variables that are controlled by outer loop structures. In such cases special attention must be paid to the interface between the structures.
Stop
Process_k
Process_k+1
InterfaceLogic_k
Process_1
Start
![Page 34: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/34.jpg)
Repetition : NestingProblem: Find the average of the averages of
lists of non-negative real numbers.
Each sublist will be terminated by a negative value
Each sublist must contain at least one non-negative value, except the last (final) sublistThe last sublist will consist only of the delimiter
sentinel negative number. This allows for the scenario where a user starts the program and then decides not to enter any values – they must enter a negative number, however.
1.04.3-15.637.5326.18.3-3.14159975.64478.524.6789-53.5-1.0
1.04.3-15.637.5326.18.3-3.14159975.64478.524.6789-53.5-1.0
![Page 35: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/35.jpg)
Repetition : Nesting Problem: Find the average of the averages of lists of non-
negative real numbers.
Variables: int NumLists, Num ;
float Value, Ave, Sum, AveSum, AveAve ;
Initializations:Start of Program: Within Program:
NumLists = 0 ; Num = 0 ; AveSum = 0.0 ; Sum = 0.0 ;
1.04.3-15.637.5326.18.3-3.14159975.64478.524.6789-53.5-1.0
![Page 36: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/36.jpg)
Repetition : NestingAverage of a sub-list terminated by negative sentinel:
Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ;
1.04.3-15.637.5326.18.3-3.14159975.64478.524.6789-53.5-1.0
![Page 37: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/37.jpg)
Repetition : NestingAverage of a sub-list terminated by negative sentinel:
Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ;
Treat this code as a unit (module).
![Page 38: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/38.jpg)
Repetition : NestingAverage of sub-list averages (terminated by negative
sentinel):
NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ if ( Num > 0 ) { AveSum = AveSum + Ave ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
1.04.3-15.637.5326.18.3-3.14159975.64478.524.6789-53.5-1.0
![Page 39: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/39.jpg)
Repetition : NestingMerge codes together:
NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ; if ( Num > 0 ) { AveSum = AveSum + Ave ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ; if ( Num > 0 ) { AveSum = AveSum + Ave ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
To complete the program, place the code into main and
add necessary #include and
documentation.
![Page 40: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/40.jpg)
Repetition : Nesting NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ; if ( Num > 0 ) { AveSum = AveSum + Ave ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
It may be useful to examine the code
to clean up any obvious
inefficiences.
![Page 41: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/41.jpg)
Repetition : Nesting NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) { Ave = Sum / Num ; AveSum = AveSum + Ave ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
It may be useful to examine the code
to clean up any obvious
inefficiences.
![Page 42: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/42.jpg)
Repetition : Nesting NumLists = 0 ; AveSum = 0.0 ; do { /* Input sublist and find its average */ Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number (<0 to quit) : ” ; scanf( “%f”, &Value ) ; if ( Value >= 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) { AveSum += Sum / Num ; NumLists++ ; } } while ( Num > 0 ) ; if ( NumLists > 0 ) AveAve = AveSum / NumLists ; printf ( “Average of averages = %f\n”, AveAve ) ;
It may be useful to examine the code
to clean up any obvious
inefficiences.
![Page 43: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/43.jpg)
Repetition : NestingBe systematic
Top-DownBottom-UpStepwise Refinement
Test your algorithms and codingsUse simple tests first, then add complexityMake sure special cases are treated
Clean up code once you have the basic idea working.
![Page 44: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/44.jpg)
Repetition : for for ( init_stmt ; cond_expr ; update_stmt )
statement ;
for ( init_stmt ; cond_expr ; update_stmt ) { statement1 ; ...... statementN ; }
COND
INITIALIZE
PROCESS
UPDATE
T
F
![Page 45: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/45.jpg)
Repetition : forExample: Find the sum of all integers from 1 to 10.
int Sum = 0, k ;
for ( k = 1 ; k <= 10 ; k++ ) Sum = Sum + k ;
![Page 46: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/46.jpg)
Repetition : forExample: Find the sum of all integers from 1 to 10.
int Sum, k ;
for ( k = 1, Sum = 0 ; k <= 10 ; k++ ) Sum = Sum + k ;
This form has the advantage that it localizes the initialization of Sum to the actual location of the for structureOtherwise, the programmer might forget to do this if the
for is repeated within the program
![Page 47: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/47.jpg)
Repetition : forExample: Find the sum of all odd integers from 1 to
10.
int Sum, k ;
for ( k = 1, Sum = 0 ; k <= 10 ; k += 2 ) Sum = Sum + k ;
![Page 48: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/48.jpg)
Repetition : forExample: Find the sum of all odd integers from 1 to
10.
int Sum, k ;
/* OR, recognizing that (2k-1) is always odd */
for ( k = 1, Sum = 0 ; k <= 5 ; k++) Sum = Sum + k + k - 1 ;
![Page 49: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/49.jpg)
Repetition : forSimplified syntax:
for ( Slot1 ; Slot2 ; Slot3 ) Stmt ;
Each Slot may contain an executable expression or assignment expression
Each Slot may be emptyUse with careful planning and make sure you know
what you are doingThe Stmt is optional
There may be no Stmt, but the semi-colon is mandatory!
![Page 50: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/50.jpg)
Repetition : forComplex syntax:
for ( init_list ; cond ; update_list ) .....
for ( init_list ; init_cond ; update_list ) .....
![Page 51: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/51.jpg)
Repetition : for for ( init_list ; cond ; update_list ) .....
In C, a list is a set of elements separated by commas
The first component (slot) of the for structure may be used to initialize several variablesThe elements may be executable expressions and
assignment expressions
for ( k = 1, Sum = 0 ; k <= 10 ; k++ ) Sum = Sum + k ;
![Page 52: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/52.jpg)
Repetition : for for ( init_list ; cond ; update_list ) .....
The last component (slot) of the for structure may be used to update several variablesThe elements may be executable expressions and
assignment expressions
for ( k = 1, Sum = 0 ; k <= 10 ; k++, Sum += k ) ;
![Page 53: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/53.jpg)
Repetition : for for ( init_list ; init_cond ; update_list ) .....
The middle component (slot) of the for structure may be used to initialize (assign) a value to a variable and then test it as a condition
for ( ; (Ch = getchar()) && ((Ch != ‘q’) || (Ch != ‘Q’)) ; ) printf ( “Enter q or Q to quit >” ;
![Page 54: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/54.jpg)
Repetition : forThe for control structure has an interesting
relationship to CPU register hardware and code optimization
Consider: for ( k = 0 ; k < N ; k++ ) Statement ;
If the variable k is modified only by the for structure and if N is left constant (invariant) within the Statement, the CPU performs all updates on k and comparisons (k<N) within the CPU registers. This avoids the need to transfer data back and forth from
RAM to CPU and thereby saves time.
RAM CPUBUS
![Page 55: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/55.jpg)
3D. Break
![Page 56: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/56.jpg)
Break and ContinueC defines two instruction statements that cause
immediate, non-sequential alteration of normal sequential instruction processing
Break LogicExecution of a break ; statement at any location in a loop-structure
causes immediate exit from the loop-structure. Break is also used to exit from a switch structure.
Continue LogicExecution of a continue ; statement at any location in a loop-
structure causes execution to continue at the beginning of the loop structure (at the next loop iteration) while skipping the remaining statements.
![Page 57: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/57.jpg)
Break and ContinueContinue Logic
Execution of a continue ; statement at any location in a loop-structure causes execution to continue at the beginning of the loop structure (at the next loop iteration) while skipping the remaining statements.
for ( k = 0 ; k < 5 ; k++ ) { if ( k == 3 ) continue ; printf ( “%d, ”, k ) ; }
Produces output : 0, 1, 2, 4
![Page 58: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/58.jpg)
BreakBreak Logic
Execution of a break ; statement at any location in a loop-structure causes immediate exit from the loop-structure
for ( k = 0 ; k < 10 ; k++ ) { if ( k == 5 ) break ; printf ( “%d, ”, k ) ; }
Produces output : 0, 1, 2, 3, 4
![Page 59: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/59.jpg)
BreakBreak Logic
Execution of a break ; statement at any location in a switch-structure causes immediate exit from the switch-structure
switch ( cond ) { ...... Case 53 : Stmt ; ..... break ; ...... }
![Page 60: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/60.jpg)
And now for something completely different ...
Enter
![Page 61: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/61.jpg)
3E. Input and Output
Standard I/O and Redirected file I/O, Formatting output
![Page 62: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/62.jpg)
Standard I/OThe C language provides definition of several
functions and pre-defined constants in the <stdio.h> library system
These are used for programming input and output of data through the standard I/O system
printf, putchar (stdout)
scanf, getchar (stdin) EOF (end of file constant)
Ctrl D
(Unix systems)
![Page 63: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/63.jpg)
Standard I/OOutput (stdout) :
Normally (default) the standard output device is the computer’s monitor (VDU: video display unit)More rarely, a printer may be the standard output device
Most monitors use a matrix of picture elements, or pixels. A beam of electrons is swept repeatedly across and down
the screen, interacting with the chemicals at the pixel locations causing them to flouresce for brief moments.
The screen is refreshed many times each second, thereby fooling the brain.
![Page 64: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/64.jpg)
Standard I/OOutput (stdout) :
Groups of pixels (rectangular areas) are used to represent graphical symbols such as printed characters.
The technical aspects of programming the computer have been solved. The appropriate programming functions are provided in the standard input output library
#include <stdio.h>
![Page 65: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/65.jpg)
Standard I/O putchar()The putchar function is useful for outputting single
characters. The need to do this occurs quite often.Text processingSpecial forms of output from programs
char Ch = ‘w’ ;
putchar( Ch ) ;
Outputs a single character: wThe cursor position is immediately after the outputted
character
![Page 66: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/66.jpg)
Standard I/O printf()The printf function is used for outputting text
Characters (strings of characters)Conversion of integer and real valued data from
machine representations to printable formsControl characters
Example:
printf ( “The average of %d and %d is %f\n”, A, B, (A+B)*0.5 ) ;
![Page 67: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/67.jpg)
Standard I/O printf()General Syntax:
printf ( FormatString [, Op1 [ , ... OpN ]] ) ;
FormatString :: a string of characters, including control characters, and data format specifier codes
OpK :: a set of operands (the K’th operand)Operands may be variables, computable expressions or functions
Operands are optional, but the number of operands must match the number of specifier codes.
![Page 68: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/68.jpg)
Standard I/O printf()The printf() function is straightforward to use for simple
applications
Prompts : printf( “Enter a value:” ) ;
Non-formatted output
printf( “Sum of %d and %d is %d\n”, A, B, A+B ) ;
More complicated applications must include formatting of the output to produce better looking reports.
![Page 69: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/69.jpg)
Standard I/OIn contrast to output, input is handled by the
standard input system (stdin).
Input one character to a char variable Ch:
Ch = getchar() ;
Input of numeric data, or more than one character (a character string) is accomplished using
scanf()
![Page 70: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/70.jpg)
Standard I/O scanf()The scanf() function permits input of various kinds
of data
Each data type to be inputted is indicated by a data type specifier code
%d %f %c %lf
Actual input must be provided in character (text) form.
![Page 71: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/71.jpg)
Standard I/O EOF<stdio.h> provides definition of a special
constant, called the end-of-file marker, EOF.
The actual value of EOF may vary on different systems, but is typically the value -1.
The getchar() and scanf() functions return a value which can be assigned to a variable (int or char)This variable can then be compared with EOF to “detect”
the end-of-file condition
while ( ( Ch = getchar() ) != EOF ) { ..... }
![Page 72: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/72.jpg)
Redirected File I/OThe standard I/O system of Unix allows the re-
direction of I/O from typical devices (KBD, VDU) to files.
This is accomplished at the command line when the program is started
%a.out < infile.dat
%a.out > outfile.dat
%a.out < infile.dat > outfile.dat
![Page 73: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/73.jpg)
Redirected File I/ORedirected I/O disconnects the default I/O
Input: cannot use KBDOutput: cannot use VDU
If redirected output is used, the output must be sent to a text file. This file can then be read using an editor.
If redirected input is used, the input text file must be prepared beforehand using an editor.
![Page 74: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/74.jpg)
Formatted OutputFormatting of output is discussed in Chapter 9 of
the required textbook for the course.
Students are assigned this chapter to read and experiment with.Chapter 9.1 – 9.6, 9.8, 9.10If time permits, we will discuss this further in the
lectureLaboratory exercises will provide additional
practice, as will assignments.
![Page 75: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/75.jpg)
3 : Summary
![Page 76: 60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details](https://reader035.vdocuments.mx/reader035/viewer/2022062518/56649f0d5503460f94c207aa/html5/thumbnails/76.jpg)
Lecture 3: SummaryAssigned Reading
PREVIOUS: Concepts, data, algorithms, basic C language
Chapters 1-3 (complete)BASICS:
Structured programming Program control
Chapter 4 (complete) Standard I/O and Formatted Output
Chapter 9.1 – 9.6, 9.8, 9.10
NEXT: Functions – Chapter 5