Title: 60-140 Lecture 3
1Program Control - Details
- 60-140 Lecture 3
- Dr. Robert D. Kent
2Lecture 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
33A Program control
- Generalities versus Details
4Generalities versus Details
- 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
5Generalities 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
63B. Decision Control
- Nested if-else and Switch
73b Outline
- Review
- Nested if-else control structures
- The switch control structure
8Review
- 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
9Review
- If Statement is compound, use braces and
indentation - if ( condition ) Statement1
...... StatementN - Indentation improves the readability (hence,
understanding) of the code for humans.
10Review
- 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
11Review
- 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 gt 50) ? A
B )
12Multiple 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
13Multiple selection A simple sort
CPU instructions are binary for relational
comparisons and logic operations. Thus, an
expression like A gt B B gt C requires three
(3) separate operations, namely Temp1
AgtB Temp2 BgtC Exprvalue Temp1 Temp2
- Solution
- int A, B, C scanf( ddd, A, B, C )
- if ( A gt B B gt C ) printf( d d d\n, A,
B, C ) if ( A gt C C gt B ) printf( d d
d\n, A, C, B ) if ( B gt A A gt C )
printf( d d d\n, B, A, C ) if ( B gt C
C gt A ) printf( d d d\n, B, C, A ) if (
C gt A A gt B ) printf( d d d\n, C, A, B )
if ( C gt B B gt A ) printf( d d d\n,
C, B, A ) - Note the number of distinct operations
- Can this be improved upon (made more efficient)?
3 x 6 18
14Multiple selection A simple sort
- Improved Solution
- if ( A gt B ) if ( B gt C ) printf( d d
d\n, A, B, C ) else if ( A gt C )
printf( d d d\n, A, C, B )
else printf( d d d\n, C, A, B ) else if
( A gt C ) printf( d d d\n, B, A, C )
else if ( B gt 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.
15Multiple 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
16Multiple 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
17Multiple selection if-else
- Solution using if-else
- printf ( Enter operation code gt )
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
18Multiple selection switch
- Solution using switch
- printf ( Enter operation code gt )
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
19Multiple 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 lt b lt ... lt
z A lt B lt ... lt Z
20Multiple 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 gt b Ch lt z)
(Ch gt B Ch lt Z)
) Alphacnt
break
21Multiple selection switch
getchar() is a function from ltstdio.hgt 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.
- 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 gt b Ch lt z)
(Ch gt B Ch lt Z)
) Alphacnt
break
22Multiple 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 gt b Ch lt z)
(Ch gt B Ch lt Z)
) Alphacnt
break
Use of break implies that the switch must be
immediately exited.
23Multiple 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 gt b Ch lt z)
(Ch gt B Ch lt Z)
) Alphacnt
break
Logic Patterns! - reused
24Multiple selection switch
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
- 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 gt b Ch lt z)
(Ch gt B Ch lt 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.
25Multiple 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 gt b Ch lt z)
(Ch gt B Ch lt 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.
26Multiple 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.
273C. Repetition Control
283c Outline
- Review
- Nested while and do-while control structures
- The for control structure
293c. 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
30Repetition while
- while ( condition_expression ) statement
- while ( condition_expression )
statement1 ...... statementN
31Repetition do-while
- do statement while (
condition_expression ) - do statement1 ......
statementN while ( condition_expression
) - MUST execute the body (process) at least once!
32Repetition Nesting
- Consider a do-while that contains another
do-while structure
Nested do-while loop.
33Repetition 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.
34Repetition Nesting
1.0 4.3 -1 5.63 7.532 6.1 8.3 -3.14159 975.64 478.
5 24.6789 -53.5 -1.0
1.0 4.3 -1 5.63 7.532 6.1 8.3 -3.14159 975.64 478.
5 24.6789 -53.5 -1.0
- 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.
35Repetition Nesting
1.0 4.3 -1 5.63 7.532 6.1 8.3 -3.14159 975.64 478.
5 24.6789 -53.5 -1.0
- 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
36Repetition Nesting
1.0 4.3 -1 5.63 7.532 6.1 8.3 -3.14159 975.64 478.
5 24.6789 -53.5 -1.0
- Average of a sub-list terminated by negative
sentinel - Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if ( Value gt 0 )
Sum Sum Value Num
while ( Value gt 0 ) if (
Num gt 0 ) Ave Sum / Num
37Repetition Nesting
- Average of a sub-list terminated by negative
sentinel - Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if ( Value gt 0 )
Sum Sum Value Num
while ( Value gt 0 ) if (
Num gt 0 ) Ave Sum / Num - Treat this code as a unit (module).
38Repetition Nesting
1.0 4.3 -1 5.63 7.532 6.1 8.3 -3.14159 975.64 478.
5 24.6789 -53.5 -1.0
- Average of sub-list averages (terminated by
negative sentinel) - NumLists 0 AveSum 0.0 do
/ Input sublist and find its average /
if ( Num gt 0 ) AveSum AveSum Ave
NumLists while (
Num gt 0 ) if ( NumLists gt 0 ) AveAve
AveSum / NumLists printf ( Average of
averages f\n, AveAve )
39Repetition Nesting
NumLists 0 AveSum 0.0 do
/ Input sublist and find its average /
Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if (
Value gt 0 ) Sum Sum Value
Num
while ( Value gt 0 ) if ( Num gt 0 ) Ave
Sum / Num if ( Num gt 0 )
AveSum AveSum Ave NumLists
while ( Num gt 0 ) if ( NumLists
gt 0 ) AveAve AveSum / NumLists printf (
Average of averages f\n, AveAve )
- 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 (lt0 to quit)
scanf( f, Value ) if (
Value gt 0 ) Sum Sum Value
Num
while ( Value gt 0 ) if ( Num gt 0 ) Ave
Sum / Num if ( Num gt 0 )
AveSum AveSum Ave NumLists
while ( Num gt 0 ) if ( NumLists
gt 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.
40Repetition Nesting
NumLists 0 AveSum 0.0 do
/ Input sublist and find its average /
Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if (
Value gt 0 ) Sum Sum Value
Num
while ( Value gt 0 ) if ( Num gt 0 ) Ave
Sum / Num if ( Num gt 0 )
AveSum AveSum Ave NumLists
while ( Num gt 0 ) if ( NumLists
gt 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.
41Repetition Nesting
NumLists 0 AveSum 0.0 do
/ Input sublist and find its average /
Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if (
Value gt 0 ) Sum Sum Value
Num
while ( Value gt 0 ) if ( Num gt 0 )
Ave Sum / Num AveSum
AveSum Ave NumLists
while ( Num gt 0 ) if ( NumLists gt 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.
42Repetition Nesting
NumLists 0 AveSum 0.0 do
/ Input sublist and find its average /
Num 0 Sum 0.0 do
printf( Enter a number (lt0 to quit)
scanf( f, Value ) if (
Value gt 0 ) Sum Sum Value
Num
while ( Value gt 0 ) if ( Num gt 0 )
AveSum Sum / Num
NumLists while ( Num gt 0
) if ( NumLists gt 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.
43Repetition 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.
44Repetition for
- for ( init_stmt cond_expr update_stmt )
statement - for ( init_stmt cond_expr update_stmt )
statement1 ......
statementN
F
T
45Repetition for
- Example Find the sum of all integers from 1 to
10. - int Sum 0, k for ( k 1 k lt
10 k ) Sum Sum k
46Repetition for
- Example Find the sum of all integers from 1 to
10. - int Sum, k for ( k 1, Sum 0 k
lt 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
47Repetition for
- Example Find the sum of all odd integers from
1 to 10. - int Sum, k for ( k 1, Sum 0 k
lt 10 k 2 ) Sum Sum k
48Repetition 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 lt 5 k) Sum Sum k k - 1
49Repetition 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!
50Repetition for
- Complex syntax
- for ( init_list cond update_list ) .....
- for ( init_list init_cond update_list )
.....
51Repetition 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 lt 10 k )
Sum Sum k
52Repetition 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 lt 10 k, Sum k
)
53Repetition 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 gt
54Repetition for
RAM
CPU
- The for control structure has an interesting
relationship to CPU register hardware and code
optimization - Consider for ( k 0 k lt 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 (kltN) within the CPU
registers. - This avoids the need to transfer data back and
forth from RAM to CPU and thereby saves time.
BUS
553D. Break
56Break 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.
57Break 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 lt 5 k )
if ( k 3 ) continue
printf ( d, , k ) - Produces output 0, 1, 2, 4
58Break
- 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 lt 10 k )
if ( k 5 ) break printf
( d, , k ) - Produces output 0, 1, 2, 3, 4
59Break
- 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
613E. Input and Output
- Standard I/O and Redirected file I/O, Formatting
output
62Standard I/O
- The C language provides definition of several
functions and pre-defined constants in the
ltstdio.hgt 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)
(Unix systems)
63Standard I/O
- Output (stdout)
- Normally (default) the standard output device is
the computers 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.
64Standard 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 ltstdio.hgt
65Standard 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
66Standard 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, (AB)0.5 )
67Standard 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 Kth operand)
- Operands may be variables, computable expressions
or functions - Operands are optional, but the number of operands
must match the number of specifier codes.
68Standard 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,
AB ) - More complicated applications must include
formatting of the output to produce better
looking reports.
69Standard 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()
70Standard 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.
71Standard I/O EOF
- ltstdio.hgt 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 ) .....
72Redirected 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 lt infile.dat
- a.out gt outfile.dat
- a.out lt infile.dat gt outfile.dat
73Redirected 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.
74Formatted 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.
753 Summary
76Lecture 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