0% found this document useful (0 votes)
5 views

Part 2-Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Part 2-Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

1

Control Structures

 2003 Prentice Hall, Inc. All rights reserved.


2

Introduction

• Before writing a program


– Have a thorough understanding of problem
– Carefully plan your approach for solving it
• While writing a program
– Know what “building blocks” are available
– Use good programming principles

 2003 Prentice Hall, Inc. All rights reserved.


3

Control Structures

• Sequential execution
– Statements executed in order
• Transfer of control
– Next statement executed not next one in sequence
• 3 control structures (Bohm and Jacopini)
– Sequence structure
• Programs executed sequentially by default
– Selection structures
• if, if/else, switch
– Repetition structures
• while, do/while, for

 2003 Prentice Hall, Inc. All rights reserved.


4

Control Structures

• C++ keywords
– Cannot be used as identifiers or variable names
C++ Keywords

Keywords common to the


C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t

 2003 Prentice Hall, Inc. All rights reserved.


5

if Selection Structure

• Translation into C++


If student’s grade is greater than or equal to 60
Print “Passed”

if ( grade >= 60 )
cout << "Passed";

 2003 Prentice Hall, Inc. All rights reserved.


6

if/else Selection Structure

• if
– Performs action if condition true
• if/else
– Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";

 2003 Prentice Hall, Inc. All rights reserved.


7

if/else Selection Structure

• Nested if/else structures


• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";

 2003 Prentice Hall, Inc. All rights reserved.


8

if/else Selection Structure

• Compound statement
– Set of statements within a pair of braces
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
• Block
– Set of statements within braces

 2003 Prentice Hall, Inc. All rights reserved.


9

while Repetition Structure

• Repetition structure
– Action repeated while some condition remains true
– Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;

 2003 Prentice Hall, Inc. All rights reserved.


10
Formulating Algorithms (Counter-Controlled
Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches certain value
• Definite repetition
– Number of repetitions known
• Example
A class of ten students took a quiz. The grades (integers in
the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.

 2003 Prentice Hall, Inc. All rights reserved.


11
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-controlled repetition.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 // function main begins program execution
10 int main()
11 {
12 int total; // sum of grades input by user
13 int gradeCounter; // number of grade to be entered next
14 int grade; // grade value
15 int average; // average of grades
16
17 // initialization phase
18 total = 0; // initialize total
19 gradeCounter = 1; // initialize loop counter
20

 2003 Prentice Hall, Inc. All rights reserved.


12
21 // processing phase
22 while ( gradeCounter <= 10 ) { // loop 10 times
23 cout << "Enter grade: "; // prompt for input
24 cin >> grade; // read grade from user
25 total = total + grade; // add grade to total
26 gradeCounter = gradeCounter + 1; // increment counter
27 }
28
29 // termination phase
30 average = total / 10; // integer division
31
32 // display result
33 cout << "Class average is " << average << endl;
The counter gets incremented each
34 time the loop executes. Eventually,
35 return 0; // indicate program ended successfully the counter causes the loop to end.
36
37 } // end function main

Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
 2003 Prentice Hall, Inc. All rights reserved.
13
Formulating Algorithms (Sentinel-Controlled
Repetition)
• Suppose problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run
– Unknown number of students
– How will program know when to end?
• Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel input
– Sentinel chosen so it cannot be confused with regular input
• -1 in this case

 2003 Prentice Hall, Inc. All rights reserved.


14
1 // Fig. 2.9: fig02_09.cpp
2 // Class average program with sentinel-controlled repetition.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::fixed;
9
10 #include <iomanip> // parameterized stream manipulators
11
12 using std::setprecision; // sets numeric output precision
13
14 // function main begins program execution
15 int main()
16 {
17 int total; // sum of grades
18 int gradeCounter; // number of grades entered Data type double used to represent
19 int grade; // grade value decimal numbers.
20
21 double average; // number with decimal point for average
22
23 // initialization phase
24 total = 0; // initialize total
25 gradeCounter = 0; // initialize loop counter

 2003 Prentice Hall, Inc. All rights reserved.


15
26
27 // processing phase
28 // get first grade from user
29 cout << "Enter grade, -1 to end: "; // prompt for input
30 cin >> grade; // read grade from user
31
32 // loop until sentinel value read from user
33 while ( grade != -1 ) {
34 total = total + grade; // add grade to total
35 gradeCounter = gradeCounter + 1; // increment counter
36
37 cout << "Enter grade, -1 to end: "; // prompt for input
38 cin >> grade; // read next grade
39
40 } // end while
41
42 // termination phase
43 // if user entered at least one grade ...
44 if ( gradeCounter != 0 ) {
45
46 // calculate average of all grades entered
47 average = static_cast< double >( total ) / gradeCounter;
48

static_cast<double>() treats total as a double temporarily


(casting).
Required because dividing two integers truncates the remainder.
gradeCounter is an int, but it gets promoted to double.
 2003 Prentice Hall, Inc. All rights reserved.
16
49 // display average with two digits of precision
50 cout << "Class average is " << setprecision( 2 )
51 << fixed << average << endl;
52
53 } // end if part of if/else
54
55 else // if no grades were entered, output appropriate message
56 cout << "No grades were entered" << endl;
57
58 return 0; // indicate program ended successfully
59
60 } // end function main setprecision(2)prints two digits past decimal point
(rounded to fit precision).
Enter grade, -1 to end: 75
Enter grade, -1 to end: 94 Programs that use this must include <iomanip>
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
fixed forces output to print in fixed point format
Enter grade, -1 to end: 64 (not scientific notation). Also, forces trailing zeros
Enter grade, -1 to end: 83 and decimal point to print.
Enter grade, -1 to end: 89 Include <iostream>
Enter grade, -1 to end: -1
Class average is 82.50

 2003 Prentice Hall, Inc. All rights reserved.


17

Assignment Operators

• Assignment expression abbreviations


– Addition assignment operator
c = c + 3; abbreviated to
c += 3;
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
 2003 Prentice Hall, Inc. All rights reserved.
18

Increment and Decrement Operators


• Increment operator (++) - can be used instead of c
+= 1
• Decrement operator (--) - can be used instead of c -
= 1
– Preincrement
• When the operator is used before the variable (++c or ––c)
• Variable is changed, then the expression it is in is evaluated.
– Posincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is changed.

 2003 Prentice Hall, Inc. All rights reserved.


19

Increment and Decrement Operators

• Increment operator (++)


– Increment variable by one
– c++
• Same as c += 1
• Decrement operator (--) similar
– Decrement variable by one
– c--

 2003 Prentice Hall, Inc. All rights reserved.


20

Increment and Decrement Operators

• Preincrement
– Variable changed before used in expression
• Operator before variable (++c or --c)
• Postincrement
– Incremented changed after expression
• Operator after variable (c++, c--)

 2003 Prentice Hall, Inc. All rights reserved.


21

Increment and Decrement Operators

• If c = 5, then
– cout << ++c;
• c is changed to 6, then printed out
– cout << c++;
• Prints out 5 (cout is executed before the increment.
• c then becomes 6

 2003 Prentice Hall, Inc. All rights reserved.


22

Increment and Decrement Operators

• When variable not in expression


– Preincrementing and postincrementing have same effect
++c;
cout << c;
and
c++;
cout << c;

are the same

 2003 Prentice Hall, Inc. All rights reserved.


23
1 // Fig. 2.14: fig02_14.cpp
2 // Preincrementing and postincrementing.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int c; // declare variable
12
13 // demonstrate postincrement
14 c = 5; // assign 5 to c
15 cout << c << endl; // print 5
16 cout << c++ << endl; // print 5 then postincrement
17 cout << c << endl << endl; // print 6
18
19 // demonstrate preincrement
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // preincrement then print 6
23 cout << c << endl; // print 6 5
24 5
25 return 0; // indicate successful termination 6
26
27 } // end function main 5
6
6
 2003 Prentice Hall, Inc. All rights reserved.
24

for Repetition Structure


• General format when using for loops
for ( initialization; LoopContinuationTest;
increment )
statement

• Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
– Prints integers from one to ten
No
semicolon
after last
statement

 2003 Prentice Hall, Inc. All rights reserved.


25
1 // Fig. 2.17: fig02_17.cpp
2 // Counter-controlled repetition with the for structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 // Initialization, repetition condition and incrementing
12 // are all included in the for structure header.
13
14 for ( int counter = 1; counter <= 10; counter++ )
15 cout << counter << endl;
16
17 return 0; // indicate successful termination
18
19 } // end function main

1
2
3
4
5
6
7
8
9
10 2003 Prentice Hall, Inc. All rights reserved.
26

for Repetition Structure


• for loops can usually be rewritten as while loops
initialization;
while ( loopContinuationTest){
statement
increment;
}

• Initialization and increment


– For multiple variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;

 2003 Prentice Hall, Inc. All rights reserved.


27

switch Multiple-Selection Structure


• switch
– Test variable for multiple values
– Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or == value3
statements
break;

default: // taken if variable matches no other cases


statements
break;
}

 2003 Prentice Hall, Inc. All rights reserved.


28

switch Multiple-Selection Structure

• Example upcoming
– Program to read grades (A-F)
– Display number of each grade entered
• Details about characters
– Single characters typically stored in a char data type
• char a 1-byte integer, so chars can be stored as ints
– Can treat character as int or char
• 97 is the numerical representation of lowercase ‘a’ (ASCII)
• Use single quotes to get numerical representation of character
cout << "The character (" << 'a' << ") has the value "
<< static_cast< int > ( 'a' ) << endl;
Prints
The character (a) has the value 97

 2003 Prentice Hall, Inc. All rights reserved.


29
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 // function main begins program execution
10 int main()
11 {
12 int grade; // one grade
13 int aCount = 0; // number of As
14 int bCount = 0; // number of Bs
15 int cCount = 0; // number of Cs
16 int dCount = 0; // number of Ds
17 int fCount = 0; // number of Fs
18
19 cout << "Enter the letter grades." << endl
20 << "Enter the EOF character to end input." << endl;
21

 2003 Prentice Hall, Inc. All rights reserved.


30
22 // loop until user types end-of-file key sequence
23 while ( ( grade = cin.get() ) != EOF ) {
24
25 // determine which grade was input cin.get() uses dot notation
26 switch ( grade ) { // switch structure nested in while
(explained chapter 6). This
27
function gets 1 character from the
28 case 'A': // grade was uppercase A
29 case 'a': // or lowercase a
keyboard (after Enter pressed), and
30 ++aCount; // increment aCount
it is assigned to grade.
31 break; // necessary to exit switch
32 cin.get() returns EOF (end-of-
33 case 'B': // grade was uppercase B file) after the EOF character is
34 case 'b': // or lowercase b input, to indicate the end of data.
35 ++bCount; // increment bCount EOF may be ctrl-d or ctrl-z,
36 break; // exit switch
depending on your OS.
37
38 case 'C': // grade was uppercase C
break causes switch to
39 case 'c': // or lowercase c
40 ++cCount; // increment cCount
end and the program continues
41 break; // exit switch with the first statement after the
42 switch structure.

Compares grade (an int)


to the numerical
representations of A and a.

 2003 Prentice Hall, Inc. All rights reserved.


31
43 case 'D': // grade was uppercase D
44 case 'd': // or lowercase d
45 ++dCount; // increment dCount
46 break; // exit switch
47
48 case 'F': // grade was uppercase F
49 case 'f': // or lowercase f
50 ++fCount; // increment fCount
51 break; // exit switch
This test is necessary because
52 Enter is pressed after each
53 case '\n': // ignore newlines, letter grade is input. This adds
54 case '\t': // tabs, a newline character that must
55 case ' ': // and spaces in input be removed. Likewise, we
56 break; // exit switch want to ignore any
57 whitespace.
58 default: // catch all other characters
59 cout << "Incorrect letter grade entered."
60 << " Enter a new grade." << endl;
61 break; // optional; will exit switch anyway
62
63 } // end switch
64
65 } // end while
66 Notice the default statement, which
catches all other cases.

 2003 Prentice Hall, Inc. All rights reserved.


32
67 // output summary of results
68 cout << "\n\nTotals for each letter grade are:"
69 << "\nA: " << aCount // display number of A grades
70 << "\nB: " << bCount // display number of B grades
71 << "\nC: " << cCount // display number of C grades
72 << "\nD: " << dCount // display number of D grades
73 << "\nF: " << fCount // display number of F grades
74 << endl;
75
76 return 0; // indicate successful termination
77
78 } // end function main

 2003 Prentice Hall, Inc. All rights reserved.


33
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
^Z

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1

 2003 Prentice Hall, Inc. All rights reserved.


34

do/while Repetition Structure

• Similar to while structure


– Makes loop continuation test at end, not beginning
– Loop body executes at least once
• Format
do {
statement
} while ( condition );

 2003 Prentice Hall, Inc. All rights reserved.


35
1 // Fig. 2.24: fig02_24.cpp
2 // Using the do/while repetition structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int counter = 1; // initialize counter
12
13 do {
14 cout << counter << " "; // display counter
15 } while ( ++counter <= 10 ); // end do/while Notice the preincrement in
16
17 cout << endl;
loop-continuation test.
18
19 return 0; // indicate successful termination
20
21 } // end function main

1 2 3 4 5 6 7 8 9 10

 2003 Prentice Hall, Inc. All rights reserved.


36

Logical Operators

• Used as conditions in loops, if statements


• && (logical AND)
– true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;

• || (logical OR)
– true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;

 2003 Prentice Hall, Inc. All rights reserved.


37

Logical Operators

• ! (logical NOT, logical negation)


– Returns true when its condition is false, & vice versa
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;

 2003 Prentice Hall, Inc. All rights reserved.


38
Confusing Equality (==) and Assignment (=)
Operators
• Common error
– Does not typically cause syntax errors
• Aspects of problem
– Expressions that have a value can be used for decision
• Zero = false, nonzero = true
– Assignment statements produce a value (the value to be
assigned)

 2003 Prentice Hall, Inc. All rights reserved.


39

Structured-Programming Summary

• All programs broken down into


– Sequence
– Selection
• if, if/else, or switch
• Any selection can be rewritten as an if statement
– Repetition
• while, do/while or for
• Any repetition structure can be rewritten as a while statement

 2003 Prentice Hall, Inc. All rights reserved.

You might also like