Beruflich Dokumente
Kultur Dokumente
Outline
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.10
2.11
2.12
2.13
2.14
2.15
Introduction
Algorithms
Pseudocode
Control Structures
if Selection Structure
if/else Selection Structure
while Repetition Structure
Formulating Algorithms: Case Study 1 (Counter-Controlled
Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)
Assignment Operators
Increment and Decrement Operators
Essentials of Counter-Controlled Repetition
for Repetition Structure
Examples Using the for Structure
Outline
2.16
2.17
2.18
2.19
2.20
2.21
2.1 Introduction
Before writing a program
Have a thorough understanding of problem
Carefully plan your approach for solving it
2.2
Algorithms
Computing problems
Solved by executing a series of actions in a specific order
Program control
2.3
Pseudocode
Pseudocode
Artificial, informal language used to develop algorithms
Similar to everyday English
2.4
Control Structures
Sequential execution
Statements executed in order
Transfer of control
Next statement executed not next one in sequence
Selection structures
if, if/else, switch
Repetition structures
2.4
Control Structures
C++ keywords
Cannot be used as identifiers or variable names
C++ Keywords
Keywordscommontothe
CandC++programming
languages
auto
continue
enum
if
short
switch
volatile
break
default
extern
int
signed
typedef
while
case
do
float
long
sizeof
union
char
double
for
register
static
unsigned
const
else
goto
return
struct
void
C++onlykeywords
asm
delete
inline
private
static_cast
try
wchar_t
bool
dynamic_cast
mutable
protected
template
typeid
catch
class
explicit false
namespacenew
public
reinterpret_cast
this
throw
typename using
const_cast
friend
operator
true
virtual
2.4
Control Structures
Flowchart
Graphical representation of an algorithm
Special-purpose symbols connected by arrows (flowlines)
Rectangle symbol (action symbol)
Any type of action
Oval symbol
Beginning or end of a program, or a section of code (circles)
2.5
if Selection Structure
Selection structure
Choose among alternative courses of action
Pseudocode example:
If students grade is greater than or equal to 60
Print Passed
2.5
if Selection Structure
if structure
Single-entry/single-exit
2003 Prentice Hall, Inc. All rights reserved.
10
2.5
if Selection Structure
true
print Passed
zero - false
nonzero - true
Example:
false
3 - 4 is true
11
2.6
if
Performs action if condition true
if/else
Different actions if conditions true or false
Pseudocode
if students 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.
12
2.6
false
print Failed
Value if true
grade >= 60
Value if false
true
print Passed
13
2.6
14
2.6
Example
if ( grade >= 90 )
cout << "A";
else if ( grade >= 80 )
cout << "B";
else if ( grade >= 70 )
cout << "C";
else if ( grade >= 60 )
cout << "D";
else
cout << "F";
// 90 and above
// 80-89
// 70-79
// 60-69
// less than 60
15
2.6
Compound statement
Set of statements within a pair of braces
if ( grade
cout <<
else {
cout <<
cout <<
>= 60 )
"Passed.\n";
"Failed.\n";
"You must take this course again.\n";
Without braces,
cout << "You must take this course again.\n";
always executed
Block
16
2.7
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
Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
17
2.7
false
true
product = 2 * product
18
2.8
Counter-controlled repetition
Loop repeated until counter reaches certain value
Definite repetition
Number of repetitions known
Example
19
2.8
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Outline
fig02_07.cpp
(1 of 2)
using std::cout;
using std::cin;
using std::endl;
// function main begins
int main()
{
int total;
//
int gradeCounter; //
int grade;
//
int average;
//
program execution
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
2
1
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// processing phase
while ( gradeCounter <= 10 ) {
cout << "Enter grade: ";
cin >> grade;
total = total + grade;
gradeCounter = gradeCounter + 1;
}
// termination phase
average = total / 10;
//
//
//
//
//
Outline
loop 10 times
prompt for input
read grade from user
add grade to total
increment counter
fig02_07.cpp
(2 of 2)
fig02_07.cpp
output (1 of 1)
// integer division
// display result
cout << "Class average is " << average << endl;
return 0;
// indicate
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class
grade: 98
grade: 76
grade: 71
grade: 87
grade: 83
grade: 90
grade: 57
grade: 79
grade: 82
grade: 94
average is 81
2
2
2.9
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
23
2.9
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
24
2.9
Processing
Input data, adjusts program variables
Termination
Calculate and print the final results
25
2.9
Processing
26
2.9
Termination
Calculate and print the class average
goes to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print No grades were entered
27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
fig02_09.cpp
(1 of 3)
std::cout;
std::cin;
std::endl;
std::fixed;
#include <iomanip>
using std::setprecision;
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
2
8
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// processing phase
// get first grade from user
cout << "Enter grade, -1 to end: ";
cin >> grade;
Outline
// prompt for input
// read grade from user
fig02_09.cpp
(2 of 3)
as a
// termination phase
// if user entered at least one grade ...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = static_cast< double >( total ) / gradeCounter;
2
9
49
50
51
52
53
54
55
56
57
58
59
60
Outline
fig02_09.cpp
(3 of 3)
fig02_09.cpp
output (1 of 1)
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
average is 82.50
75
94
97
88
70
64
83
89
-1
setprecision(2)prints
two digits past
fixed forces output
to print
decimal
in fixed point format
(not point (rounded to fit precision).
scientific notation). Also,
that use this must include <iomanip>
forces trailing zerosPrograms
and
decimal point to print.
Include <iostream>
3
0
Notice that
Program processes 10 results
Fixed number, use counter-controlled loop
If not 1, assume 2
31
First refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition
should be raised
Refine
Initialize variables
to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
2003 Prentice Hall, Inc. All rights reserved.
32
Input the ten quiz grades and count passes and failures
to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
33
Program next
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
fig02_11.cpp
(1 of 2)
using std::cout;
using std::cin;
using std::endl;
// function main begins program execution
int main()
{
// initialize variables in declarations
int passes = 0;
// number of passes
int failures = 0;
// number of failures
int studentCounter = 1;
// student counter
int result;
// one exam result
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) {
// prompt user for input and obtain value from user
cout << "Enter result (1 = pass, 2 = fail): ";
cin >> result;
3
5
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Outline
fig02_11.cpp
(2 of 2)
// successful termination
3
6
Enter result
Enter result
Enter result
Enter result
Enter result
Enter result
Enter result
Enter result
Enter result
Enter result
Passed 6
Failed 4
(1
(1
(1
(1
(1
(1
(1
(1
(1
(1
=
=
=
=
=
=
=
=
=
=
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
2
2
2
2
2
2
2
2
2
2
=
=
=
=
=
=
=
=
=
=
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
1
2
2
1
1
1
2
1
1
2
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Passed 9
Failed 1
Raise tuition
=
=
=
=
=
=
=
=
=
=
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
2
2
2
2
2
2
2
2
2
2
=
=
=
=
=
=
=
=
=
=
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
1
1
1
1
2
1
1
1
1
1
Outline
fig02_11.cpp
output (1 of 1)
3
7
can be rewritten as
variable operator= expression;
d
e
f
g
-=
*=
/=
%=
4
5
3
9
(d
(e
(f
(g
=
=
=
=
d
e
f
g
*
/
%
4)
5)
3)
9)
38
Posincrement
39
40
Postincrement
Incremented changed after expression
41
42
and
c++;
cout << c;
43
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Outline
fig02_14.cpp
(1 of 2)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int c;
// declare variable
// demonstrate postincrement
c = 5;
//
cout << c << endl;
//
cout << c++ << endl;
//
cout << c << endl << endl; //
assign 5 to c
print 5
print 5 then postincrement
print 6
// demonstrate preincrement
c = 5;
//
cout << c << endl;
//
cout << ++c << endl;
//
cout << c << endl;
//
assign 5 to c
print 5
preincrement then print 6
print 6
4
4
24
25
26
27
return 0;
Outline
5
5
6
fig02_14.cpp
(2 of 2)
fig02_14.cpp
output (1 of 1)
5
6
6
4
5
46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Outline
fig02_16.cpp
(1 of 1)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int counter = 1;
// initialization
while ( counter <= 10 ) {
cout << counter << endl;
++counter;
// repetition condition
// display counter
// increment
} // end while
return 0;
4
7
Outline
1
2
3
4
5
6
7
8
9
10
fig02_16.cpp
output (1 of 1)
4
8
Names counter
Declares counter to be an integer
Reserves space for counter in memory
Sets counter to an initial value of 1
49
50
Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
No
semicolon
after last
statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Outline
fig02_17.cpp
(1 of 1)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
// Initialization, repetition condition and incrementing
// are all included in the for structure header.
for ( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
return 0;
5
1
Outline
1
2
3
4
5
6
7
8
9
10
fig02_17.cpp
output (1 of 1)
5
2
53
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Outline
fig02_20.cpp
(1 of 1)
using std::cout;
using std::endl;
fig02_20.cpp
output (1 of 1)
// output sum
// successful termination
Sum is 2550
5
4
55
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Outline
fig02_21.cpp
(1 of 2)
std::cout;
std::endl;
std::ios;
std::fixed;
#include <iomanip>
using std::setw;
using std::setprecision;
#include <cmath>
5
6
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Outline
5
7
Year
1
2
3
4
5
6
7
8
9
10
Outline
Amount on deposit
1050.00
1102.50
1157.63
1215.51
1276.28
1340.10
1407.10
1477.46
1551.33
1628.89
fig02_21.cpp
output (1 of 1)
5
8
59
case a
true
case a action(s)
break
case b action(s)
break
case z action(s)
break
false
case b
true
false
.
.
.
case z
false
default action(s)
true
60
Prints
61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Outline
fig02_22.cpp
(1 of 4)
using std::cout;
using std::cin;
using std::endl;
// function main begins program execution
int main()
{
int grade;
// one grade
int aCount = 0; // number of As
int bCount = 0; // number of Bs
int cCount = 0; // number of Cs
int dCount = 0; // number of Ds
int fCount = 0; // number of Fs
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
6
2
22
// loop until user types end-of-file key sequence
23
while ( ( grade = cin.get() ) != EOF ) { break causes switch to end and
24
the program continues with the first
25
// determine which grade was input
statement after the switch structure.
fig02_22.cpp
26
switch ( grade ) { // switch structure nested in while
(2 of 4)
27
28
case 'A':
// grade was uppercase A
cin.get() uses dot notation
29
case 'a':
// or lowercase a
(explained chapter 6). This
30
++aCount;
// increment aCount
function gets 1 character from the
31
break;
// necessary to exit switch
Assignment statements have a keyboard (after Enter pressed), and
32
value,was
which
is the same
it is assigned to grade.
33
case 'B':
// grade
uppercase
B as
thelowercase
variable onb the left of the
34
case 'b':
// or
=. The value
of this statement
35
++bCount;
// increment
bCount
cin.get() returns EOF (end-of36
break;
// exit
is theswitch
same as the value
file) after the EOF character is
Compares grade (an int) to
37
returned by cin.get().
input, to indicate the end of data.
the numericalcase
representations
38
'C':
// grade was uppercase C
EOF may be ctrl-d or ctrl-z,
39of A and a. case 'c':
// or lowercase c
This can also be used to
depending on your OS.
40
++cCount;
// increment cCount
initialize multiple variables:
41
break;
// exit switch
a = b = c = 0;
42
Outline
6
3
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
case 'D':
case 'd':
++dCount;
break;
//
//
//
//
Outline
fig02_22.cpp
(3 of 4)
case 'F':
case 'f':
++fCount;
break;
//
//
//
//
case '\n':
case '\t':
case ' ':
break;
//
//
// and spaces in input
Notice the default
// exit switch
statement, which
catches all other cases.
default:
// catch all other characters
cout << "Incorrect letter grade entered."
<< " Enter a new grade." << endl;
break;
// optional; will exit switch anyway
} // end switch
} // end while
6
4
67
68
69
70
71
72
73
74
75
76
77
78
Outline
A
B
C
D
F
grades
grades
grades
grades
grades
fig02_22.cpp
(4 of 4)
6
5
Outline
fig02_22.cpp
output (1 of 1)
6
6
67
Format
do {
statement
} while ( condition );
action(s)
true
condition
false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
Outline
fig02_24.cpp
(1 of 1)
using std::cout;
using std::endl;
fig02_24.cpp
output (1 of 1)
10
6
8
Common uses
69
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
fig02_26.cpp
(1 of 2)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int x;
// loop 10 times
for ( x = 1; x <= 10; x++ ) {
// if x is 5, terminate loop
if ( x == 5 )
break;
// break loop only if x is 5
cout << x << " ";
// display value of x
} // end for
cout << "\nBroke out of loop when x became " << x << endl;
7
0
26
27
28
29
return 0;
Outline
1 2 3 4
Broke out of loop when x became 5
fig02_26.cpp
(2 of 2)
fig02_26.cpp
output (1 of 1)
7
1
for structure
72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
fig02_27.cpp
(1 of 2)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
// loop 10 times
for ( int x = 1; x <= 10; x++ ) {
// if x is 5, continue with
if ( x == 5 )
continue;
// skip remaining code in loop body
cout << x << " ";
// display value of x
7
3
26
27
Outline
fig02_27.cpp
(2 of 2)
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
fig02_27.cpp
output (1 of 1)
7
4
|| (logical OR)
true if either of condition is true
75
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
76
Aspects of problem
Expressions that have a value can be used for decision
Zero = false, nonzero = true
77
78
Rvalues
Only appear on right side of equation
Constants, such as numbers (i.e. cannot write 4 = x;)
79
80
Rule 3
Rule 3
Rule 3
81
Repetition
82