Upload
lawlietll
View
221
Download
0
Embed Size (px)
Citation preview
8/13/2019 Ece246 Chapter 3
1/73
ECE 246(INTRODUCTION TO C
PROGRAMMING)CHAPTER 3:
CONTROL FLOW
8/13/2019 Ece246 Chapter 3
2/73
Learning Outcomes Able to understand the assignment variations
Able to understand the usage selection
statements/structures Able to understand the usage of repetition
statements/structures
Able to understand the usage ofcontinue/break
8/13/2019 Ece246 Chapter 3
3/73
Lesson Outline Assignment variations
Selection statements: if, if else, switch
Repetition statements: for, while, do while
Break/continue
8/13/2019 Ece246 Chapter 3
4/73
8/13/2019 Ece246 Chapter 3
5/73
Lets Recap Computing problems
All can be solved by executing a series of actions in a
specific order
Algorithm: procedure in terms of
Actions to be executed
The order in which these actions are to be executed
Program control
Specify order in which statements are to be executed
8/13/2019 Ece246 Chapter 3
6/73
Lets Recap Pseudocode
Artificial, informal language that helps us
develop algorithms Similar to everyday English
Not actually executed on computers
Helps us think out a program before writing it Easy to convert into a corresponding C++ program
Consists only of executable statements
8/13/2019 Ece246 Chapter 3
7/73
More Assignment Operators Assignment operators abbreviate assignment expressions
c = c + 3;
can be abbreviated as c += 3;using the addition assignment operator
Statements of the formvariable=variableoperatorexpression;can be rewritten as
variableoperator=expression;
Examples of other assignment operators:
d -= 4 (d = d - 4)e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
8/13/2019 Ece246 Chapter 3
8/73
8
Assignmentoperator
Sampleexpression
Explanation Assigns
Assume:intc = 3,d = 5,e = 4,f = 6,g = 12;+= c += 7 C = c + 7 10to c-= d -= 4 D = d - 4 1to d*= e *= 5 E = e * 5 20to e/= f /= 3 F = f / 3 2to f%= g %= 9 G = g % 9 3to g
More Arithmetic assignment operators.
8/13/2019 Ece246 Chapter 3
9/73
Increment and Decrement Operators Increment operator (++)
Can be used instead of c+=1
Decrement operator (--)
Can be used instead of c-=1
Preincrement
Operator is used before the variable (++cor --c)
Variable is changed before the expression it is in is evaluated
Postincrement Operator is used after the variable (c++or c--)
Expression executes before the variable is changed
8/13/2019 Ece246 Chapter 3
10/73
Increment and Decrement Operators If cequals 5, then
printf( "%d", ++c );
Prints 6
printf( "%d", c++ );
Prints 5
In either case, cnow has the value of 6
When variable not in an expression
Preincrementing and postincrementing have the same effect
++c;
printf( %d, c );
Has the same effect asc++;
printf( %d, c );
8/13/2019 Ece246 Chapter 3
11/73
11
Operator Sample expression Explanation
++ ++a Increment aby 1, then use the new value of ain theexpression in which aresides.
++ a++ Use the current value of ain the expression in which aresides, then increment aby 1.
-- --b Decrement bby 1, then use the new value of bin theexpression in which bresides.
-- b-- Use the current value ofbin the expression in which bresides, then decrement bby 1.
Increment and decrement operators.
8/13/2019 Ece246 Chapter 3
12/73
The ifselection statement Selection structure:
Used to choose among alternative courses of action
Pseudocode:
If students grade is greater than or equal to 60Print Passed
If condition true
Print statement executed and program goes on to next
statement If false, print statement is ignored and the program
goes onto the next statement
Indenting makes programs easier to read
C ignores whitespace characters
8/13/2019 Ece246 Chapter 3
13/73
The if selection statement
Pseudocode statement in C:if ( grade >= 60 )
printf( "Passed\n" );
C code corresponds closely to the pseudocode
Diamond symbol (decision symbol)
Indicates decision is to be made
Contains an expression that can be trueor false
Test the condition, follow appropriate path
8/13/2019 Ece246 Chapter 3
14/73
Flowcharting the single-selection ifstatement.
8/13/2019 Ece246 Chapter 3
15/73
The ifelseselection statement if
Only performs an action if the condition is true
ifelse
Specifies an action to be performed both whenthe condition is trueand when it is false
Psuedocode:
If students grade is greater than or equal to 60Print Passed
elsePrint Failed
Note spacing/indentation conventions
8/13/2019 Ece246 Chapter 3
16/73
If statement Exercise: Expected Output
/* demonstrates the usage of if */
#include
int main()
{
const float limit = 3000.0;
int id_num;float miles;
printf("Please type in the car number and mileage:\n");
scanf("%d\n %f\n",&id_num,&miles);
if (miles > limit)printf("Car %d is over the limit.\n",id_num);
printf("End of program output");
return 0;
}
8/13/2019 Ece246 Chapter 3
17/73
The ifelseselection statement
Sample of C code:
if ( grade >= 60 )
printf( "Passed\n");else
printf( "Failed\n");
8/13/2019 Ece246 Chapter 3
18/73
Flowcharting the double-selection if elsestatement.
8/13/2019 Ece246 Chapter 3
19/73
If else statement Exercise: Expected Output
/* demonstrates the usage of if else*/
#include
int main()
{
float radius;
printf("Please type in the radius\n");
scanf(%f\n",&radius);
if (radius < 0.0)
printf(A negative radius is invalid.\n);
elseprintf(Thearea of this circle is %f,(3.14*radius*radius));
return 0;
}
8/13/2019 Ece246 Chapter 3
20/73
The ifelseselection statement
Nested ifelsestatements
Test for multiple cases by placing ifelse
selection statements inside ifelseselectionstatement
Once condition is met, rest of statements skipped
8/13/2019 Ece246 Chapter 3
21/73
The ifelseselection statement Pseudocode for a nested ifelsestatement
If students grade is greater than or equal to 90Print A
elseIf students grade is greater than or equal to 80Print B
elseIf students grade is greater than or equal to 70
Print CelseIf students grade is greater than or equal to 60
Print Delse
Print F
8/13/2019 Ece246 Chapter 3
22/73
The ifelseselection statement Compound statement:
Set of statements within a pair of braces
Example:
if ( grade >= 60 )printf( "Passed.\n" );else {
printf( "Failed.\n" );printf( "You must take this course
again.\n" );}
Without the braces, the statement printf( "You must take this course
again.\n" );
would be executed automatically
8/13/2019 Ece246 Chapter 3
23/73
Nested If else statement Exercise1: Expected Output
/* demonstrates the usage of nested if else*/
#include
int main()
{
char code;
printf("Enter a specification code\n");scanf("%c\n",&code);
if (code == 'S')
printf("The item is space exploration grade.\n");
else if (code == 'M')
printf("The item is military grade.\n");
else if (code == 'C')printf("The item is commercial grade.\n");
else if (code == 'T')
printf("The item is toy grade.\n");
else
printf("An invalid code was entered.\n");
return 0;
}
8/13/2019 Ece246 Chapter 3
24/73
8/13/2019 Ece246 Chapter 3
25/73
switchMultiple-Selection Statement
switch Useful when a variable or expression is tested for all the values it can
assume and different actions are taken
Format Series of caselabels and an optional defaultcase
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break;exits from statement
8/13/2019 Ece246 Chapter 3
26/73
switch multiple-selection statement withbreaks.
8/13/2019 Ece246 Chapter 3
27/73
Nested If else statement Exercise2: Expected Output/* demonstrates the usage of switch*/
#include
int main()
{
int opselect;
float fnum, snum;
printf("Please type in two numbers\n");
scanf("%f\n%f\n",&fnum,&snum);
printf("Enter a select code:\n");printf("1 For addition:\n2 For multiplication:\n3 For division:\n");
scanf("%d\n",&opselect);
switch (opselect)
{
case 1:
printf("The sum of the numbers entered is %f", fnum+snum);
break;case 2:
printf("The product of the numbers entered is %f", fnum*snum);
break;
case 3:
printf("The first number divided by the second is %f", (fnum/snum));
break;
}
return 0;
}
8/13/2019 Ece246 Chapter 3
28/73
Good Programming Practice
Provide a defaultcase in switchstatements. Cases not explicitly tested in
a switchare ignored. The defaultcase helps prevent this by focusing the
programmer on the need to process
exceptional conditions. There aresituations in which no defaultprocessing is needed.
8/13/2019 Ece246 Chapter 3
29/73
8/13/2019 Ece246 Chapter 3
30/73
Good Programming Practice
In a switchstatement when thedefaultclause is listed last, the
breakstatement is not required.But some programmers include this
breakfor clarity and symmetry
with other cases.
8/13/2019 Ece246 Chapter 3
31/73
Repetition Statement Essentials
Loop
Group of instructions computer executes repeatedly while
some condition remains true
Counter-controlled repetition
Definite repetition: know how many times loop will
execute
Control variable used to count repetitions
Sentinel-controlled repetition
Indefinite repetition
Used when number of repetitions not known
Sentinel value indicates "end of data"
8/13/2019 Ece246 Chapter 3
32/73
Counter-Controlled Repetition - while
Counter-controlled repetition requires
The name of a control variable (or loop counter)
The initial value of the control variable An increment (or decrement) by which the
control variable is modified each time through the
loop
A condition that tests for the final value of the
control variable (i.e., whether looping should
continue)
8/13/2019 Ece246 Chapter 3
33/73
Counter-Controlled Repetition - while
Example:int counter = 1; // initialization
while ( counter
8/13/2019 Ece246 Chapter 3
34/73
2 Counter-controlled repetition */3 #include4
5 /* function main begins program execution */6 intmain( void)7 {8 intcounter = 1; /* initialization */9
10 while( counter
8/13/2019 Ece246 Chapter 3
35/73
Counter-Controlled Repetition
Condensed code
C Programmers would make the program more
concise Initialize counterto 0
while ( ++counter
8/13/2019 Ece246 Chapter 3
36/73
Good Programming Practices
Control counting loops with integer values.
Indent the statements in the body of each controlstatement.
Put a blank line before and after each control statement tomake it stand out in a program.
Too many levels of nesting can make a program difficultto understand. As a general rule, try to avoid using morethan three levels of nesting.
The combination of vertical spacing before and aftercontrol statements and indentation of the bodies of controlstatements within the control-statement headers gives
programs a two-dimensional appearance that greatly
improves program readability.
8/13/2019 Ece246 Chapter 3
37/73
forstatement header components.
1 /* Fig. 4.2: fig04_02.c
8/13/2019 Ece246 Chapter 3
38/73
2 Counter-controlled repetition with the for statement */3 #include4
5 /* function main begins program execution */6 intmain( void)7 {8 intcounter; /* define counter */9
10 /* initialization, repetition condition, and increment11 are all included in the for statement header. */12 for( counter = 1; counter
8/13/2019 Ece246 Chapter 3
39/73
Error-Prevention Tip
Using the final value in the condition of a
whileor forstatement and using the
8/13/2019 Ece246 Chapter 3
40/73
forRepetition Statement
Format when using forloopsfor( initialization; loopContinuationTest; increment)
statement
Example:for( int counter = 1; counter
8/13/2019 Ece246 Chapter 3
41/73
forRepetition Statement For loops can usually be rewritten as while loops:
initialization;while( loopContinuationTest) {statement;increment;
}
Initialization and increment
Can be comma-separated lists
Example:for (int i = 0, j = 0; j + i
8/13/2019 Ece246 Chapter 3
42/73
Common Programming Errors
Using commas instead of semicolons
in a forheader is a syntax error.
Placing a semicolon immediately to
the right of a forheader makes thebody of that forstatement an empty
statement. This is normally a logicerror.
8/13/2019 Ece246 Chapter 3
43/73
forStatement :Notes and Observations
Arithmetic expressions
Initialization, loop-continuation, and increment can contain arithmeticexpressions. If xequals 2and yequals 10
for ( j = x; j
8/13/2019 Ece246 Chapter 3
44/73
Error-Prevention Tip
Although the value of the control
variable can be changed in the body
of a forloop, this can lead to subtleerrors. It is best not to change it.
8/13/2019 Ece246 Chapter 3
45/73
Flowcharting a typical forrepetition statement.
8/13/2019 Ece246 Chapter 3
46/73
Exercise: Expected Output
/* by using for */#include
/* function main begins program execution */
int main( void )
{
int counter; /* declaration */
/* for statement header */
for ( counter = 2; counter
8/13/2019 Ece246 Chapter 3
47/73
Good Programming Practices
Although statements preceding a forandstatements in the body of a forcan often bemerged into the forheader, avoid doing sobecause it makes the program more difficult to
read.
Limit the size of control-statement headers to a
single line if possible.
8/13/2019 Ece246 Chapter 3
48/73
/* by using for */
#include
/* function main begins program execution */int main( void )
{
const int MAXNUM = 10; /* declaration of constant value*/
int num;
printf("NUMBER\tSQUARE\tCUBE\n------\t------\t----\n");
for ( num = 1; num
8/13/2019 Ece246 Chapter 3
49/73
Error-Prevention Tip
Do not use variables of type floatordoubleto perform monetary
calculations. The impreciseness offloating-point numbers can cause errors
that will result in incorrect monetary
values.
8/13/2019 Ece246 Chapter 3
50/73
dowhileRepetition Statement
The dowhilerepetition statement
Similar to the whilestructure
Condition for repetition only tested after the bodyof the loop is performed
All actions are performed at least once
Format:
do {
statement;
} while (condition);
8/13/2019 Ece246 Chapter 3
51/73
dowhileRepetition Statement
Example (letting counter = 1):do {
printf( "%d ", counter );
} while (++counter
8/13/2019 Ece246 Chapter 3
52/73
Good Programming Practice
Some programmers always include
braces in a do...whilestatement
even if the braces are not necessary.This helps eliminate ambiguity between
the do...whilestatement
containing one statement and thewhilestatement.
8/13/2019 Ece246 Chapter 3
53/73
Common Programming Error
Infinite loops are caused when the loop-continuation condition in a while, forordo...whilestatement never becomesfalse. To prevent this, make sure there is nota semicolon immediately after the header ofa whileor forstatement. In a counter-controlled loop, make sure the control
variable is incremented (or decremented) inthe loop. In a sentinel-controlled loop, makesure the sentinel value is eventually input.
1 /* Fig. 4.9: fig04_09.c2
8/13/2019 Ece246 Chapter 3
54/73
2 Using the do/while repetition statement */3 #include4
5 /* function main begins program execution */6 intmain( void)7 {8 intcounter = 1; /* initialize counter */9
10 do{11 printf( %d , counter ); /* display counter */12 } while( ++counter
8/13/2019 Ece246 Chapter 3
55/73
Flowcharting the do whilerepetition statement.
8/13/2019 Ece246 Chapter 3
56/73
breakand continue
Statements break
Causes immediate exit from a while, for,
dowhileor switchstatement
Program execution continues with the first
statement after the structure
Common uses of the breakstatement
Escape early from a loop
Skip the remainder of a switchstatement
1 /* Fig. 4.11: fig04_11.c2 Using the break statement in a for statement */
8/13/2019 Ece246 Chapter 3
57/73
3 #include4
5 /* function main begins program execution */6 intmain( void)7 {8 intx; /* counter */9
10 /* loop 10 times */11 for( x = 1; x
8/13/2019 Ece246 Chapter 3
58/73
breakand continue
Statements continue
Skips the remaining statements in the body of a
while, foror dowhilestatement
Proceeds with the next iteration of the loop
whileand dowhile
Loop-continuation test is evaluated immediately after
the continuestatement is executed for
Increment expression is executed, then the loop-
continuation test is evaluated
1 /* Fig. 4.12: fig04_12.c2 Using the continue statement in a for statement */
8/13/2019 Ece246 Chapter 3
59/73
3 #include4
5 /* function main begins program execution */6 intmain( void)7 {8 intx; /* counter */9
10 /* loop 10 times */11 for( x = 1; x
8/13/2019 Ece246 Chapter 3
60/73
Logical Operators
&&( logical AND )
Returns trueif both conditions are true
||( logical OR )
Returns trueif either of its conditions are true
!( logical NOT, logical negation )
Reverses the truth/falsity of its condition
Unary operator, has one operand
Useful as conditions in loopsExpression Result
true && false falsetrue || false true
!false true
8/13/2019 Ece246 Chapter 3
61/73
expression1 expression2 expression1 &&expression20 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Truth table for the (logical AND)
operator.
8/13/2019 Ece246 Chapter 3
62/73
8/13/2019 Ece246 Chapter 3
63/73
expression !expression
0 1
nonzero 0
Truth table for operator !
(logical negation).
8/13/2019 Ece246 Chapter 3
64/73
Performance Tip
In expressions using operator &&, make
the condition that is most likely to be false
the leftmost condition. In expressionsusing operator ||, make the condition thatis most likely to be true the leftmost
condition. This can reduce a programsexecution time.
8/13/2019 Ece246 Chapter 3
65/73
Operators Associativity Type
++ (postfix) -- (postfix) right to left postfix+ - ++(prefix) -- (prefix) (type) right to left unary* / % left to right multiplicative+ - left to right additive< >= left to right relational== = left to right equality&& left to right logical AND|| left to right logical OR?: right to left conditional= += -= *= /= %= right to left assignment, left to right comma
Operator precedence and
associativity.
f i li ( ) d
8/13/2019 Ece246 Chapter 3
66/73
Confusing Equality (==) andAssignment (=) Operators
Dangerous error
Does not ordinarily cause syntax errors
Any expression that produces a value can be usedin control structures
Nonzero values are true, zero values are false
Example using ==:if ( payCode == 4 )
printf( "You get a bonus!\n" );
Checks payCode, if it is 4then a bonus is awarded
C f i li ( ) d
8/13/2019 Ece246 Chapter 3
67/73
Confusing Equality (==) andAssignment (=) Operators
Example, replacing ==with =:if ( payCode = 4 )
printf( "You get a bonus!\n" );
This sets payCodeto 4
4is nonzero, so expression is true, and bonus awarded no
matter what the payCodewas
Logic error, not a syntax error
C f i E li ( ) d
8/13/2019 Ece246 Chapter 3
68/73
Confusing Equality (==) andAssignment (=) Operators lvalues
Expressions that can appear on the left side of an equation
Their values can be changed, such as variable names
x = 4;
rvalues
Expressions that can only appear on the right side of an equation
Constants, such as numbers
Cannot write 4 = x;
Must write x = 4; lvalues can be used as rvalues, but not vice versa
y = x;
8/13/2019 Ece246 Chapter 3
69/73
Structured Programming Summary
All programs can be broken down into 3 controls
Sequencehandled automatically by compiler
Selectionif, ifelseor switch
Repetitionwhile, dowhileor for Any selection can be rewritten as an ifstatement, and
any repetition can be rewritten as a whilestatement
8/13/2019 Ece246 Chapter 3
70/73
Review ExercisesWrite individual for statements for the following cases:
Use a counter named i that has an initial value
of 1, a final value of 20, and an increment of 1
Use a counter named icount that has an initial
value of 1, a final value of 20, and an
increment of 2
Use a counter namedj that has an initial value
of 1, a final value of 100, and an increment of
5
8/13/2019 Ece246 Chapter 3
71/73
Review Exercises continueWrite individual for statements for the following cases:
Use a counter named icount that has an initial
value of 20, a final value of 1, and an
increment of -1
Use a counter named icount that has an initial
value of 20, a final value of 1, and an
increment of -2
Use a counter named count that has an initial
value of 1.0, a final value of 16.2, and an
increment of 0.2
8/13/2019 Ece246 Chapter 3
72/73
Review Exercises continue
Finally, determine the number of times that each
for loop is executed for the previous for
statements.
8/13/2019 Ece246 Chapter 3
73/73
References
Burgess, M. (1999), C Programming Tutorial
(K&R version 4)
Deitel, P.J. & Deitel, H.M. (2007), C How ToProgram, Pearson International Edition
SEE YOU NEXT LESSON