1
1.21 A Simple Program:
Printing a Line of Text
• Comments
–
–
–
–
Document programs
Improve program readability
Ignored by compiler
Single-line comment
• Begin with //
• Preprocessor directives
– Processed by preprocessor before compiling
– Begin with #
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
2
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
Function main
#include <iostream>
Outline
Single-line comments
returns an
begin with //.
Preprocessor
directive to
integer
value.
Left brace
{ begins function
include
input/output Every
streamC++ statement fig01_02.cpp
begins
execution
Function
main appears
body. program
ends
(1
of 1)
header
file
<iostream>.
exactly once in every C++ with a semicolon ;.
program..
fig01_02.cpp
// function main
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
//
} // end function
Welcome to C++!
Corresponding right brace }
indicate
thatbody.
program ended successfully
ends
function
Stream
insertion
Name cout
belongs
to operator.
main namespace std.
Keyword return is one of
several means to exit
function; value 0 indicates
program terminated
successfully.
output (1 of 1)
2003 Prentice Hall, Inc.
All rights reserved.
3
1.21 A Simple Program:
Printing a Line of Text
• Standard output stream object
– std::cout
– “Connected” to screen
– <<
• Stream insertion operator
• Value to right (right operand) inserted into output stream
• Namespace
– std:: specifies using name that belongs to “namespace”
std
– std:: removed through use of using statements
• Escape characters
– \
– Indicates “special” character output
2003 Prentice Hall, Inc. All rights reserved.
4
1.21 A Simple Program:
Printing a Line of Text
Escape Sequence
Description
\n
Newline. Position the screen cursor to the
beginning of the next line.
\t
Horizontal tab. Move the screen cursor to the next
tab stop.
\r
Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a
Alert. Sound the system bell.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double quote
character.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
5
// Fig. 1.5: fig01_05.cpp
// Printing multiple lines with a single statement
#include <iostream>
// function main begins program execution Using newline characters
print on multiple lines.
int main()
{
std::cout << "Welcome\nto\n\nC++!\n";
return 0;
Outline
to
fig01_05.cpp
(1 of 1)
fig01_05.cpp
output (1 of 1)
// indicate that program ended successfully
} // end function main
Welcome
to
C++!
2003 Prentice Hall, Inc.
All rights reserved.
6
1.22 Another Simple Program:
Adding Two Integers
• Variables
– Location in memory where value can be stored
– Common data types
• int - integer numbers
• char - characters
• double - floating point numbers
• bool - values can only be true and false
– Declare variables with name and data type before use
int integer1;
int integer2;
int sum;
– Can declare several variables of same type in one declaration
• Comma-separated list
int integer1, integer2, sum;
2003 Prentice Hall, Inc. All rights reserved.
7
1.22 Another Simple Program:
Adding Two Integers
• Variables
– Variable names
• Valid identifier
– Series of characters (letters, digits, underscores)
– Cannot begin with digit
– Case sensitive
2003 Prentice Hall, Inc. All rights reserved.
8
1.22 Another Simple Program:
Adding Two Integers
• Input stream object
– >> (stream extraction operator)
• Used with std::cin
• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
• = (assignment operator)
– Assigns value to variable
– Binary operator (two operands)
– Example:
sum = variable1 + variable2;
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
9
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
Outline
// function main begins program execution
int main()
Declare integer variables.
{
int integer1; // first number to be input by user
int integer2; // second number to be input by user
Usewhich
stream
extraction
int sum;
// variable in
sum
will be stored
std::cout << "Enter first
std::cin >> integer1;
fig01_06.cpp
(1 of 1)
operator with standard input
stream to obtain
user input.
integer\n";
// prompt
// read an integer
std::cout << "Enter second integer\n"; // prompt
std::cin >> integer2;
// read
an integer
Calculations can
be performed
in output
sum = integer1 + integer2;
lines 18 and 20:
// assign result to sum
std::cout << "Sum is " <<
std::cout << "Sum is " << sum << std::endl; // print
return 0;
statements: alternative for
Stream manipulator
std::endl outputs a
newline, then “flushes output
integer1 + integer2 << std::endl;
sum buffer.”
// indicate that program ended successfully
} // end function main
Concatenating, chaining or
cascading stream insertion
operations.
2003 Prentice Hall, Inc.
All rights reserved.
Enter first integer
45
Enter second integer
72
Sum is 117
10
Outline
fig01_06.cpp
output (1 of 1)
2003 Prentice Hall, Inc.
All rights reserved.
11
1.23 Memory Concepts
• Variable names
– Correspond to actual locations in computer's memory
– Every variable has name, type, size and value
– When new value placed into variable, overwrites previous
value
– Reading variables from memory nondestructive
• An uninitialized variable
– Contains the value last stored in the memory location
reserved for that variable.
2003 Prentice Hall, Inc. All rights reserved.
12
1.23 Memory Concepts
std::cin >> integer1;
integer1
45
std::cin >> integer2;
integer1
45
– Assume user entered 72
integer2
72
integer1
45
integer2
72
– Assume user entered 45
sum = integer1 + integer2;
sum
2003 Prentice Hall, Inc. All rights reserved.
117
13
1.24
Arithmetic
• Arithmetic calculations
– *
• Multiplication
– /
• Division
• Integer division truncates remainder
– 7 / 5 evaluates to 1
– %
• Modulus operator returns remainder
– 7 % 5 evaluates to 2
2003 Prentice Hall, Inc. All rights reserved.
14
1.24
Arithmetic
• Rules of operator precedence
– Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
– Multiplication, division, modulus applied next
• Operators applied from left to right
– Addition, subtraction applied last
Operator(s)
Operation(s)
• Operators
applied fromOrder
leftoftoevaluation
right (precedence)
()
Parentheses
*, /, or %
Multiplication Division Evaluated second. If there are several, they re
Modulus
evaluated left to right.
+ or -
Addition
Subtraction
2003 Prentice Hall, Inc. All rights reserved.
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
Evaluated last. If there are several, they are
evaluated left to right.
15
1.25 Decision Making: Equality and
Relational Operators
Sta nd a rd a lg eb ra ic
eq ua lity op era tor or
rela tiona l op era tor
C++ eq ua lity
or rela tiona l
op era tor
Exa m p le
of C++
c ond ition
Mea ning of
C++ c ond ition
>
>
x > y
x is greater than y
<
<
x < y
x is less than y
>=
x >= y
x is greater than or equal to y
<=
x <= y
x is less than or equal to y
=
==
x == y
x is equal to y
!=
x != y
x is not equal to y
Relational operators
Equality operators
2003 Prentice Hall, Inc. All rights reserved.
16
1.25 Decision Making: Equality and
Relational Operators
• Equality and relational operators
– Equality operators
• Same level of precedence
– Relational operators
• Same level of precedence
– Associate left to right
• if structure
– Make decision based on truth or falsity of condition
• If condition met (true), body executed
• Else, body not executed
2003 Prentice Hall, Inc. All rights reserved.
17
1.25 Decision Making: Equality and
Relational Operators
• using statements
– Eliminate use of std:: prefix
– Write cout instead of std::cout
2003 Prentice Hall, Inc. All rights reserved.
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
18
// Fig. 1.14: fig01_14.cpp
// Using if statements, relational
// operators, and equality operators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// program uses cout
// program uses cin
// program uses endl
Outline
fig01_14.cpp
(1 of 2)
using statements eliminate
need for std:: prefix.
variables.
// function main begins programDeclare
execution
int main()
{
Can write
cout
cin
int num1; // first number
to be
readand
from
user
without
std::
prefix.
int num2; // second number to be read from user
cout << "Enter two integers, and I will tell you\n"
if structure compares values
<< "the relationships they satisfy: ";
of num1
and num2
to test for
If condition
is true
cin >> num1 >> num2;
// read
two integers
if ( num1 == num2 )
cout << num1 << " is
(i.e.,
equality.
values are equal), execute this
if structure compares
values
statement.
If condition
is true (i.e.,
of num1
andnum2
num2
test for
equal
to " <<
<< toendl;
values are not equal), execute
inequality.
this statement.
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 << endl;
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
if ( num1 < num2 )
cout << num1 << " is less than " << num2 << endl;
if ( num1 > num2 )
cout << num1 << " is greater than " << num2 << endl;
if ( num1 <= num2 )
cout << num1 << " is less than or equal to "
<< num2 << endl;
19
Outline
fig01_14.cpp
Statements
may
(2 of
2) be split over
several lines.
fig01_14.cpp
output (1 of 2)
if ( num1 >= num2 )
cout << num1 << " is greater than or equal to "
<< num2 << endl;
return 0;
// indicate that program ended successfully
} // end function main
Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
2003 Prentice Hall, Inc.
All rights reserved.
Enter two integers, and I will tell you
the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
20
Outline
fig01_14.cpp
output (2 of 2)
2003 Prentice Hall, Inc.
All rights reserved.
21
2.4
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.
22
2.4
Control Structures
• C++ keywords
– Cannot be used as identifiers or variable names
C++ Keyw o rd s
Keywords common to the
C and C++ programming
languages
auto
continue
enum
if
short
switch
volatile
C++ only keywords
asm
delete
inline
private
static_cast
try
wchar_t
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
bool
dynamic_cast
mutable
protected
template
typeid
catch
explicit
namespace
public
this
typename
class
false
new
reinterpret_cast
throw
using
const_cast
friend
operator
2003 Prentice Hall, Inc. All rights reserved.
true
virtual
23
2.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";
• Diamond symbol (decision symbol)
– Indicates decision is to be made
– Contains an expression that can be true or false
• Test condition, follow path
• if structure
– Single-entry/single-exit
2003 Prentice Hall, Inc. All rights reserved.
24
2.5
if Selection Structure
• Flowchart of pseudocode statement
A decision can be made on
any expression.
grade >= 60
true
zero - false
print “Passed”
nonzero - true
Example:
false
2003 Prentice Hall, Inc. All rights reserved.
3 - 4 is true
25
2.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.
26
2.6
if/else Selection Structure
• Ternary conditional operator (?:) (only one)
– Three arguments (condition, value if true, value if false)
• Code could be written:
cout << ( grade >= 60 ? “Passed” : “Failed” );
Condition
false
print “Failed”
2003 Prentice Hall, Inc. All rights reserved.
Value if true
grade >= 60
Value if false
true
print “Passed”
27
2.6
if/else Selection Structure
• Nested if/else structures
– One inside another, test for multiple cases
– Once condition met, other statements skipped
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
2003 Prentice Hall, Inc. All rights reserved.
28
2.6
if/else Selection Structure
• 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";
2003 Prentice Hall, Inc. All rights reserved.
// 90 and above
// 80-89
// 70-79
// 60-69
// less than 60
29
2.6
if/else Selection Structure
• 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
– Set of statements within braces
2003 Prentice Hall, Inc. All rights reserved.
30
2.7
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.
31
2.7
The while Repetition Structure
• Flowchart of while loop
true
product <= 1000
false
2003 Prentice Hall, Inc. All rights reserved.
product = 2 * product
32
2.8
Formulating Algorithms (CounterControlled 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.
33
2.8
Formulating Algorithms (CounterControlled Repetition)
• Pseudocode for example:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
• Next: C++ code for this example
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 2.7: fig02_07.cpp
// Class average program with counter-controlled repetition.
#include <iostream>
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;
//
34
program execution
sum of grades input by user
number of grade to be entered next
grade value
average of grades
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
2003 Prentice Hall, Inc.
All rights reserved.
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;
35
//
//
//
//
//
loop 10 times
prompt for input
read grade from user
add grade to total
increment counter
Outline
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
} // end function main
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
The counter gets incremented each
time the loop executes.
program ended successfully
Eventually, the counter causes the
loop to end.
If the counter is not incremented
the loop will never end.
2003 Prentice Hall, Inc.
All rights reserved.
36
2.9
Formulating Algorithms (SentinelControlled 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.
37
2.9
Formulating Algorithms (SentinelControlled Repetition)
• Top-down, stepwise refinement
– Begin with pseudocode representation of top
Determine the class average for the quiz
– Divide top into smaller tasks, list in order
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
2003 Prentice Hall, Inc. All rights reserved.
38
2.9
Formulating Algorithms (SentinelControlled Repetition)
• Many programs have three phases
– Initialization
• Initializes the program variables
– Processing
• Input data, adjusts program variables
– Termination
• Calculate and print the final results
– Helps break up programs for top-down refinement
2003 Prentice Hall, Inc. All rights reserved.
39
2.9
Formulating Algorithms (SentinelControlled Repetition)
• Refine the initialization phase
Initialize variables
goes to
Initialize total to zero
Initialize counter to zero
• Processing
Input, sum and count the quiz grades
goes to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
2003 Prentice Hall, Inc. All rights reserved.
40
2.9
Formulating Algorithms (SentinelControlled Repetition)
• 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”
• Next: C++ program
2003 Prentice Hall, Inc. All rights reserved.
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
// Fig. 2.9: fig02_09.cpp
// Class average program with sentinel-controlled repetition.
#include <iostream>
using
using
using
using
41
Outline
fig02_09.cpp
(1 of 3)
std::cout;
std::cin;
std::endl;
std::fixed;
#include <iomanip>
// parameterized stream manipulators
using std::setprecision;
// sets numeric output precision
// function main begins program execution
int main()
Data type double used to represent
{
int total;
// sum of grades decimal numbers.
int gradeCounter; // number of grades entered
int grade;
// grade value
double average;
// number with decimal point for average
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
42
// processing phase
// get first grade from user
cout << "Enter grade, -1 to end: "; // prompt for input
static_cast<double>() treats total
cin >> grade;
// read grade from user
temporarily (casting).
Outline
as a double
fig02_09.cpp
(2 of 3)
// loop until sentinel value read from user
because dividing two integers truncates the
while ( grade != -1 )Required
{
remainder. If the denominator
wastodefined
total = total + grade;
// add grade
total as a double the
gradeCounter = gradeCounter
+ 1; be
//implicitly
incrementpromoted
counter to a double for the
numerator would
calculation and the result stored as a double value in the
value.
cout << "Enter grade,
-1 to
end: ";
// isprompt
variable
average
which
definedfor
as ainput
double
cin >> grade;
// read next grade
} // end while
gradeCounter is an int, but it gets promoted to
double.
// termination phase
// if user entered at least one grade ...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = static_cast< double >( total ) / gradeCounter;
2003 Prentice Hall, Inc.
All rights reserved.
49
50
51
52
53
54
55
56
57
58
59
60
// display average with two digits of precision
cout << "Class average is " << setprecision( 2 )
<< fixed << average << endl;
} // end if part of if/else
else // if no grades were entered, output appropriate message
cout << "No grades were entered" << endl;
return 0;
43
Outline
fig02_09.cpp
(3 of 3)
fig02_09.cpp
output (1 of 1)
// indicate program ended successfully
} // end function main
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>
2003 Prentice Hall, Inc.
All rights reserved.
44
2.11 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
e
f
g
-=
*=
/=
%=
4
5
3
9
2003 Prentice Hall, Inc. All rights reserved.
(d
(e
(f
(g
=
=
=
=
d
e
f
g
*
/
%
4)
5)
3)
9)
45
2.12 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.
46
2.12 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.
47
2.12 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.
48
2.12 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.
49
2.12 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 2.14: fig02_14.cpp
// Preincrementing and postincrementing.
#include <iostream>
50
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
2003 Prentice Hall, Inc.
All rights reserved.
24
25
26
27
5
5
6
51
return 0;
// indicate successful termination
} // end function main
Outline
fig02_14.cpp
(2 of 2)
fig02_14.cpp
output (1 of 1)
5
6
6
2003 Prentice Hall, Inc.
All rights reserved.
52
2.13 Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires
–
–
–
–
Name of control variable/loop counter
Initial value of control variable
Condition to test for final value
Increment/decrement to modify control variable when
looping
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 2.16: fig02_16.cpp
// Counter-controlled repetition.
#include <iostream>
53
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;
// indicate successful termination
} // end function main
2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
54
Outline
fig02_16.cpp
output (1 of 1)
2003 Prentice Hall, Inc.
All rights reserved.
55
2.16 switch Multiple-Selection Structure
• switch
– When a variable may assume many different values which must be
tested.
– Series of case labels and optional default case
switch ( variable ) {
case value1:
statements
break;
case value2:
case value3:
statements
break;
default:
statements
break;
// taken if variable == value1
// necessary to exit switch
// taken if variable == value2 or == value3
// taken if variable matches no other cases
}
2003 Prentice Hall, Inc. All rights reserved.
56
2.16 switch Multiple-Selection Structure
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)
2003 Prentice Hall, Inc. All rights reserved.
true
57
2.17 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 );
action(s)
true
condition
false
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
// Fig. 2.24: fig02_24.cpp
// Using the do/while repetition structure.
#include <iostream>
58
Outline
fig02_24.cpp
(1 of 1)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int counter = 1;
// initialize counter
do {
cout << counter << " ";
} while ( ++counter <= 10 );
fig02_24.cpp
output (1 of 1)
Notice the preincrement in
loop-continuation test.
// display counter
// end do/while
cout << endl;
return 0;
// indicate successful termination
} // end function main
2
3
4
5
6
7
8
9
10
2003 Prentice Hall, Inc.
All rights reserved.
59
2.18 break and continue Statements
• break statement
– Immediate exit from while, for, do/while, switch
– Program continues with first statement after structure
– Should not be used in if/else
• Common uses
– Escape early from a loop
– Skip the remainder of switch
2003 Prentice Hall, Inc. All rights reserved.
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
// Fig. 2.26: fig02_26.cpp
// Using the break statement in a for structure.
#include <iostream>
60
Outline
fig02_26.cpp
(1 of 2)
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int x;
// x declared here so it can be used after the loop
// loop 10 times
for ( x = 1; x <= 10; x++ ) {
Exits for structure when
break executed.
// 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;
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
61
return 0;
// indicate successful termination
} // end function main
1 2 3 4
Broke out of loop when x became 5
Outline
fig02_26.cpp
(2 of 2)
fig02_26.cpp
output (1 of 1)
2003 Prentice Hall, Inc.
All rights reserved.
62
2.20 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.
63
2.20 Confusing Equality (==) and
Assignment (=) Operators
• Example
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
– If paycode is 4, bonus given
• If == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
– Paycode set to 4 (no matter what it was before)
– Statement is true (since 4 is non-zero)
– Bonus given in every case
2003 Prentice Hall, Inc. All rights reserved.
64
2.20 Confusing Equality (==) and
Assignment (=) Operators
• Lvalues
– Expressions that can appear on left side of equation
– Can be changed (I.e., variables)
• x = 4;
• Rvalues
– Only appear on right side of equation
– Constants, such as numbers (i.e. cannot write 4 = x;)
• Lvalues can be used as rvalues, but not vice versa
2003 Prentice Hall, Inc. All rights reserved.
© Copyright 2025 Paperzz