Download presentation
Presentation is loading. Please wait.
Published byQuentin Hamilton Modified over 9 years ago
1
60-140 Lecture 3 Dr. Robert D. Kent Program Control - Details
2
Lecture 3: Outline Program control Generalities versus details Decision control Nested if-else control structures The switch control structure Repetition control Nested while and do-while control structures The for control structure The role of functions in Top-Down design Impact on formulation of well-defined control structures
3
3A : Program control Generalities versus Details
4
Previously, we introduced the basic C control structures Decision (Selection) if if-else switch Repetition while do-while for We shall now take another look, in more detail Usage and patterns Flexibility
5
Generalities versus Details Usage and patterns How are the control structures used in simple, versus complicated, programming circumstances? What patterns emerge often? These can be re-used Flexibility How flexible is the syntax and grammar of the control structures? Efficiency versus Clarity
6
3B. Decision Control Nested if-else and Switch
7
3b: Outline Review Nested if-else control structures The switch control structure
8
Review We 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
9
Review If Statement is compound, use braces and indentation if ( condition ) { Statement1 ;...... StatementN ; } Indentation improves the readability (hence, understanding) of the code for humans.
10
Review Selection: 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 ; }
11
Review Simple Selection: ( condition ) ? T_statement : F_statement This simple selection structure uses the ternary operator ?: This form may be used as a single control structure/statement It 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’ ) ;
12
Multiple selection – A simple sort Problem: Enter three integer values and output them in the order from largest to smallest All values inputted are distinct Note – there are six (6) separate cases to account for This is called sorting Later we will discuss this for an arbitrary number of values
13
Multiple selection – A simple sort Solution: 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 operations Can 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>B Temp2 = B>C Exprvalue = Temp1 && Temp2 3 x 6 = 18
14
Multiple selection – A simple sort Improved 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 operations Can this be improved upon (made more efficient)? NO ! A minimum of 2 – a maximum of 3! Divide and Conquer (binary subdivision) strategy.
15
Multiple selection Multiple 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
16
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 as 1- Add 2- Subtract 3- Multiply 4- Divide
17
Multiple selection : if-else Solution 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 ;
18
Multiple selection : switch Solution 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 ; }
19
Multiple selection : switch Problem: 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’
20
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 ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; }
21
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 ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; } getchar() is a function from 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.
22
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 ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; } Use of break implies that the switch must be immediately exited.
23
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 ‘B’ && Ch <= ‘Z’) ) Alphacnt++ ; break ; } Logic Patterns! - reused
24
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 ‘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++ ;
25
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 ‘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.
26
Multiple selection : switch It is possible to nest multiple statements and control structures within each case clause of the switch structure Usually this leads to coding that is difficult to understand Typically, it is advised to keep the logic of each case clause relatively simple and direct Later, 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.
27
3C. Repetition Control While, Do-while and For
28
3c: Outline Review Nested while and do-while control structures The for control structure
29
3c. Repetition Repetition 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 while do-while for
30
Repetition : while while ( condition_expression ) statement ; while ( condition_expression ) { statement1 ;...... statementN ; } cond process FALSE TRUE
31
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
32
Repetition : Nesting Consider a do-while that contains another do- while structure: cond FALSE TRUE cond process FALSE TRUE Nested do-while loop.
33
Repetition : Nesting Nesting of control structures within other control structures occurs quite often in programming Loop structures require care in order to ensure that all control conditions are properly established Always 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
34
Repetition : Nesting Problem: 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) sublist The 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.0 4.3 5.63 7.532 6.1 8.3 -3.14159 975.64 478.5 24.6789 -53.5 1.0 4.3 5.63 7.532 6.1 8.3 -3.14159 975.64 478.5 24.6789 -53.5
35
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.0 4.3 5.63 7.532 6.1 8.3 -3.14159 975.64 478.5 24.6789 -53.5
36
Repetition : Nesting Average of a sub-list terminated by negative sentinel: Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number ( = 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ; 1.0 4.3 5.63 7.532 6.1 8.3 -3.14159 975.64 478.5 24.6789 -53.5
37
Repetition : Nesting Average of a sub-list terminated by negative sentinel: Num = 0 ; Sum = 0.0 ; do { printf( “Enter a number ( = 0 ) { Sum = Sum + Value ; Num++ ; } } while ( Value >= 0 ) ; if ( Num > 0 ) Ave = Sum / Num ; Treat this code as a unit (module).
38
Repetition : Nesting Average 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.0 4.3 5.63 7.532 6.1 8.3 -3.14159 975.64 478.5 24.6789 -53.5
39
Repetition : Nesting Merge 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 ) { 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.
40
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 ) { 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.
41
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 ) { 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.
42
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 ) { 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.
43
Repetition : Nesting Be systematic Top-Down Bottom-Up Stepwise Refinement Test your algorithms and codings Use simple tests first, then add complexity Make sure special cases are treated Clean up code once you have the basic idea working.
44
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
45
Repetition : for Example: Find the sum of all integers from 1 to 10. int Sum = 0, k ; for ( k = 1 ; k <= 10 ; k++ ) Sum = Sum + k ;
46
Repetition : for Example: 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 structure Otherwise, the programmer might forget to do this if the for is repeated within the program
47
Repetition : for Example: 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 ;
48
Repetition : for Example: 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 ;
49
Repetition : for Simplified syntax: for ( Slot1 ; Slot2 ; Slot3 ) Stmt ; Each Slot may contain an executable expression or assignment expression Each Slot may be empty Use with careful planning and make sure you know what you are doing The Stmt is optional There may be no Stmt, but the semi-colon is mandatory!
50
Repetition : for Complex syntax: for ( init_list ; cond ; update_list )..... for ( init_list ; init_cond ; update_list ).....
51
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 variables The elements may be executable expressions and assignment expressions for ( k = 1, Sum = 0 ; k <= 10 ; k++ ) Sum = Sum + k ;
52
Repetition : for for ( init_list ; cond ; update_list )..... The last component (slot) of the for structure may be used to update several variables The elements may be executable expressions and assignment expressions for ( k = 1, Sum = 0 ; k <= 10 ; k++, Sum += k ) ;
53
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 >” ;
54
Repetition : for The 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. RAMCPU BUS
55
3D. Break
56
Break and Continue C defines two instruction statements that cause immediate, non-sequential alteration of normal sequential instruction processing Break Logic Execution 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 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.
57
Break and Continue Continue 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
58
Break Break 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
59
Break Break 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 ;...... }
60
And now for something completely different... Enter
61
3E. Input and Output Standard I/O and Redirected file I/O, Formatting output
62
Standard I/O The C language provides definition of several functions and pre-defined constants in the 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) CtrlD (Unix systems)
63
Standard I/O Output (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.
64
Standard I/O Output (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
65
Standard I/O putchar() The putchar function is useful for outputting single characters. The need to do this occurs quite often. Text processing Special forms of output from programs char Ch = ‘w’ ; putchar( Ch ) ; Outputs a single character: w The cursor position is immediately after the outputted character
66
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 forms Control characters Example: printf ( “The average of %d and %d is %f\n”, A, B, (A+B)*0.5 ) ;
67
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.
68
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.
69
Standard I/O In 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()
70
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.
71
Standard I/O EOF 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 ) {..... }
72
Redirected File I/O The 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 outfile.dat
73
Redirected File I/O Redirected I/O disconnects the default I/O Input: cannot use KBD Output: 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.
74
Formatted Output Formatting 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.10 If time permits, we will discuss this further in the lecture Laboratory exercises will provide additional practice, as will assignments.
75
3 : Summary
76
Lecture 3: Summary Assigned 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.