Professional Documents
Culture Documents
Problem Solving With C++ 9th Edition Savitch Solutions Manual 1
Problem Solving With C++ 9th Edition Savitch Solutions Manual 1
Chapter 5
Functions for All Subtasks
1
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
One of the more important things in programming is planning, even for the simplest
program. If the planning is thorough, the coding will be easy, and the only errors likely to
be encountered are syntax errors, usually caused by either typing errors, a boundary
condition problem (frequently, an off by one error), or (we hope not) lack of knowledge of
the language details.
/*
Task: Write a function that computes average (I will call
this the arithmetic mean or simply the mean) and standard
deviation of four scores. The average or mean, avg, is
computed as
avg = ( s1 + s2 + s3 + s4 ) / 4
( s1 − a) + ( s 2 − a ) + ( s3 − a)
std_deviation =
4
Input: scores s1 s2 s3 s4
2
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
3
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
void statistics( double s1, double s2, double s3, double s4,
double& avg, double& stdDev );
int main()
{
double s1, s2, s3, s4, avg, stdDev;
char ans;
do
{
cout << "Enter 4 decimal numbers, "
4
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
5
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
mean of 1 2 3 4 is 2.5
the standard deviation of these numbers is 0.559017
y or Y continues, any other terminates
n
21:45:05:~/AW$
6
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
int main()
7
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
{
int feet;
double inches, meters;
char ans;
do
{
input ( feet, inches );
convert ( feet, inches, meters );
output ( feet, inches, meters );
cout << "Y or y continues, any other character quits "
<< endl;
cin >> ans;
} while ( 'Y' == ans || 'y' == ans );
return 0;
}
8
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
cout.setf( ios::showpoint );
cout.setf( ios::fixed );
cout.precision(2);
cout << "the value of feet, inches" << feet << ","
<< inches << endl
<< " converted to meters, centimeters is "
<< meters << endl;
}
/*
A typical run follows:
06:59:16:~/AW$ a.out
Enter feet as an integer: 5
Enter inches as a double: 7
the value of feet, inches5,7.00
converted to meters, centimeters is 1.70
9
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
10
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
11
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
int main()
{
int feet;
double inches, meters;
char ans;
do
{
input ( meters );
convert ( feet, inches, meters );
output ( feet, inches, meters );
cout << "Y or y continues, any other character quits "
<< endl;
cin >> ans;
} while ( 'Y' == ans || 'y' == ans );
return 0;
}
void input ( double& meters )
{
cout << "Enter a number of meters as a double \n";
cin >> meters;
}
12
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
cout.setf( ios::showpoint );
cout.setf( ios::fixed );
cout.precision(2);
cout << "The value of meters, centimeters " << endl
<< meters << " meters" << endl
<< "converted to English measure is " << endl
<< feet << " feet, " << inches << " inches"
<< endl;
}
/*
A typical run follows:
07:56:28:~/AW$ a.out
13
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
14
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
#include <iostream>
using namespace std;
15
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
16
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
void MetricToEnglish();
// request metric measure, converts to English, outputs both
int main()
{
char ans;
do
{
int which;
cout << "Enter 1 for English to Metric or " << endl
<< "Enter 2 for Metric to English conversion"
<< endl;
cin >> which;
if ( 1 == which )
EnglishToMetric();
else
MetricToEnglish();
17
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
void MetricToEnglish()
{
int feet;
double inches, meters;
char ans;
do
{
inputM ( meters );
convertMtoE ( feet, inches, meters );
output ( feet, inches, meters );
cout << "Y or y continues, any other character quits "
<< endl;
cin >> ans;
} while ( 'Y' == ans || 'y' == ans );
}
void EnglishToMetric ()
{
int feet;
double inches, meters;
char ans;
18
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
do
{
inputE ( feet, inches );
convertEtoM ( feet, inches, meters );
output ( feet, inches, meters );
cout << "Y or y continues, any other character quits "
<< endl;
cin >> ans;
} while ( 'Y' == ans || 'y' == ans );
}
19
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
20
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
<< feet << " feet, " << inches << " inches"
<< endl;
}
/*
A typical run follows
08:59:38:~/AW$ a.out
Enter 1 for English to Metric or
Enter 2 for Metric to English conversion
2
Enter a number of meters as a double
75
75.00 meters corresponds to 246 feet, 0.76 inches
Y or y continues, any other character quits
n
Y or y allows another choice of conversion. any other quits
y
Enter 1 for English to Metric or
Enter 2 for Metric to English conversion
1
Enter feet as an integer: 246
Enter inches as a double: 0.76
75.00 meters corresponds to 246 feet, 0.76 inches
Y or y continues, any other character quits
q
Y or y allows another choice of conversion. any other quits
q
09:00:08:~/AW$
21
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
*/
s = (a + b + c)/2
area = sqrt(s(s - a)(s - b)(s - c))
It is necessary to test whether edges of lengths a, b and c actually form a triangle. The test
for values of a, b and c to form a triangle is that each of the following inequalities be
satisfied.
a + b > c
and
b+ c > a
and
a+c > b
A question to ask the student might be: Do two of these imply the third?
The answer, (un?)fortunately, is no. All three conditions for legimate data must be checked.
The student should be able to produce an example such as a = 1, b = 1, c = 2 that
shows that the assertion, “two of these conditions implies the third”, isn’t true for all a, b
and c.
1
Hero, Heron, or Hron, was a mathematician conjectured to have lived between the 3 rd and 2nd centuries
BCE. He lived in Alexandria, but wrote in Greek. This formula is ascribed to him as is Hero’s engine, where
steam recoil rotates a sphere or wheel.
22
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
The program should confirm that the entered values of a, b, and c satisfy these condtions.
If the test shows a triangle is possible, then the area and perimeter are computed and reported.
If the test fails, the program reports this fact and exits.
a) The convert function has boundary cases that require careful attention.
b) ALL of this commentary and planning should be done PRIOR to beginning to write the
program. Once this is done the program is almost written. The sooner coding begins, the
longer the program will take to do correctly.
c) When testing for equality, as in
if (12 == hours)
put the constant first. The compiler will catch errors such as if (12= hours) which are hard
to see otherwise. I made many errors of this type while coding this problem.
23
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
#include <iostream>
using namespace std;
24
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
// AMPM = 'A';
// else
// (hours < 12)
// AMPM is set to 'A';
// hours is unchanged
int main()
{
int hours, minutes;
char AMPM, ans;
do
{
input( hours, minutes );
convert ( hours, AMPM );
output( hours, minutes, AMPM );
cout << "Enter Y or y to continue,"
<< " anything else quits."
<< endl;
cin >> ans;
} while ( 'Y'== ans || 'y' == ans );
25
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
return 0;
}
26
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
{
hours = hours + 12;
AMPM = 'A';
}
else // (hours < 12) // definitely morning hour
AMPM = 'A'; // hours is unchanged
}
27
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
y
Enter 24 hour time in the format HH:MM
Enter 24 hour time in the format HH:MM
11:30
Time in 12 hour format:
11:30 AM
Enter Y or y to continue, anything else quits.
y
Enter 24 hour time in the format HH:MM
12:30
Time in 12 hour format:
12:30 PM
Enter Y or y to continue, anything else quits.
y
Enter 24 hour time in the format HH:MM
23:59
// Notes: The 24 hour boundary, i.e., when the time wraps to the
// next day is important here.
28
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
//
// Known Bugs: If the completion time would be in a day later
// than the next day after the start, this program gives incorrect
// results.
//
#include <iostream>
char colon;
cout << "Enter 24 hour time in the format HH:MM "
<< endl;
cin >> hours24 >> colon >> minutes;
}
int main()
{
using std::cout;
using std::cin;
using std::endl;
cout << "Compute completion time from current time and waiting
period\n";
29
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
finishMinutes%= 60;
return 0;
}
/*
Typical run
y
Current time:
Enter 24 hour time in the format HH:MM
8:30
Waiting time:
30
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
n
Press any key to continue
*/
This problem is different from #2 only in the details of managing 12 hour time. The wait
time interval could be any number of hours and minutes, so the output should provide the
number of days that elapse from the start time until completion.
You may want an input routine that verifies that you have entered
legitimate 12 hour time data, i.e. hours betwee 1 and 12, minutes between 0
and 59, and includes either an A for AM or a P for PM.
Write code to convert the 12 hour start time to 24 hour time and use the code from #3 to
computer the finish time.
Decide on how to handle finish times that fall in some later day, then convert 24 hour time
to 12 hour time and output that using code from #2.
A greedy algorithm works for this problem. A greedy algorithm makes locally optimal
choices at each point in the sequence of points in the solution, in the hope that the locally
optimal choices will result in a globally optimal solution. This works surprisingly often,
31
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
including this problem. It is interesting to me that the greedy algorithm fails for some
national coinage.
I suggest that the student write code to choose the largest number of coins of the largest
denomination from the list of coin not yet used. Repeat this on the remaining amount of
money for decreasing denominations until no more coins are left.
32
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
// Windchill Index
// Wind Chill
#include <iostream>
#include <cmath>
#include <cstdlib>
//using namespace std;
33
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
int main()
{
using std::cout;
using std::cin;
//using std::pow; // quirk of MSVC++
using std::endl;
double t, v;
char ans;
do
{
cout << "Enter the Celcius termperature (<= 10
degrees)\n";
cin >> t;
cout << "Enter wind speed in meters/second: \n";
cin >> v;
34
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
/*
Typical run:
http://www.msc.ec.gc.ca/education/windchill/windchill_calcul
ator_e.cfm
*/
Programming Project 6: Duel
// **********************************************************************
35
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
//
// This program simulates the duel between Aaron, Bob, and Charlie.
// It answers parts a-c of project 6.
//
***********************************************************************
#include <iostream>
#include <cstdlib> // Needed for random numbers
// Function prototypes
void shoot(bool& targetAlive, double accuracy);
int startDuel();
// Constants
const double AARONACCURACY = 1.0/3;
const double BOBACCURRACY = 0.5;
const double CHARLIEACCURACY = 1.0;
const int NUMDUELS = 1000;
// ======================
// shoot:
// Simulates shooting at a live target,
// referenced by targetAlive, with a given accuracy.
// ======================
void shoot(bool& targetAlive, double accuracy)
{
double r;
// Only continue if the target is alive
if (targetAlive == true)
{
r = rand() % 100; // Random number from 0-99
if (r < (accuracy * 100))
{
// Hit target
targetAlive = false;
}
}
}
// ======================
// startDuel:
// Simulates a duel where Aaron shoots first and each
// contestant shoots at the best shooter still alive.
//
// Returns 0 if Aaron wins, 1 if Bob wins, 2 if Charlie wins
// ======================
int startDuel()
{
36
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
// Bobs's turn
if (bobAlive)
{
if (charlieAlive)
{
shoot(charlieAlive, BOBACCURRACY);
}
else if (aaronAlive)
{
shoot(aaronAlive, BOBACCURRACY);
}
}
// Charlie's turn
if (charlieAlive)
{
if (bobAlive)
{
shoot(bobAlive, CHARLIEACCURACY);
}
else if (aaronAlive)
{
shoot(aaronAlive, CHARLIEACCURACY);
}
}
}
if (aaronAlive) return 0;
else if (bobAlive) return 1;
else if (charlieAlive) return 2;
}
// ====================
37
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
// main function
// ====================
int main()
{
int i;
int winner;
double aaronWins=0, bobWins=0, charlieWins=0;
cout << "Using the strategy of shooting at the best shooter alive:" <<
endl;
cout << "Aaron win %: " << (aaronWins/NUMDUELS) << endl;
cout << "Bob win %: " << (bobWins/NUMDUELS) << endl;
cout << "Charlie win %: " << (charlieWins/NUMDUELS) << endl;
return 0;
}
// **********************************************************************
// Duel Part D
//
// This program simulates the duel between Aaron, Bob, and Charlie.
// It answers part d of project 15, where Aaron intentionally misses his
// first shot.
//
***********************************************************************
#include <iostream>
#include <cstdlib> // Needed for random numbers
// Function prototypes
38
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
// Constants
const double AARONACCURACY = 1.0/3;
const double BOBACCURRACY = 0.5;
const double CHARLIEACCURACY = 1.0;
const int NUMDUELS = 1000;
// ======================
// shoot:
// Simulates shooting at a live target,
// referenced by targetAlive, with a given accuracy.
// ======================
void shoot(bool& targetAlive, double accuracy)
{
double r;
// Only continue if the target is alive
if (targetAlive == true)
{
r = rand() % 100; // Random number from 0-99
if (r < (accuracy * 100))
{
// Hit target
targetAlive = false;
}
}
}
// ======================
// startDuel:
// Simulates a duel where Aaron shoots first and each
// contestant shoots at the best shooter still alive.
// To simulate Aaron missing on his first shot, Aaron is moved
// to the end of the cycle (i.e. Bob shoots first, which is equivalent
// to Aaron missing first).
//
// Returns 0 if Aaron wins, 1 if Bob wins, 2 if Charlie wins
// ======================
int startDuel()
{
bool aaronAlive = true, bobAlive = true, charlieAlive = true;
39
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
if (charlieAlive)
{
shoot(charlieAlive, BOBACCURRACY);
}
else if (aaronAlive)
{
shoot(aaronAlive, BOBACCURRACY);
}
}
// Charlie's turn
if (charlieAlive)
{
if (bobAlive)
{
shoot(bobAlive, CHARLIEACCURACY);
}
else if (aaronAlive)
{
shoot(aaronAlive, CHARLIEACCURACY);
}
}
// ====================
// main function
// ====================
int main()
{
int i;
int winner;
double aaronWins=0, bobWins=0, charlieWins=0;
40
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
cout << "Using the strategy of shooting at the best shooter alive, but
Aaron intentionally misses on the first shot:" << endl;
cout << "Aaron win %: " << (aaronWins/NUMDUELS) << endl;
cout << "Bob win %: " << (bobWins/NUMDUELS) << endl;
cout << "Charlie win %: " << (charlieWins/NUMDUELS) << endl;
return 0;
}
#include <iostream>
41
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
int main()
{
using namespace std;
int month, day, year, day_of_week;
// Output it
cout << "\nThe date " << month << "/" << day << "/" << year
<< " is a ";
if (day_of_week == 0)
{
cout << "Sunday";
}
else if (day_of_week == 1)
{
cout << "Monday";
42
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
}
else if (day_of_week == 2)
{
cout << "Tuesday";
}
else if (day_of_week == 3)
{
cout << "Wednesday";
}
else if (day_of_week == 4)
{
cout << "Thursday";
}
else if (day_of_week == 5)
{
cout << "Friday";
}
else if (day_of_week == 6)
{
cout << "Saturday";
}
cout << endl;
return 0;
}
cout << "\nPlease enter a month, day, and year, separated by" <<
endl;
cout << "spaces (e.g., '7 4 2008' for July 4, 2008): ";
cin >> month;
cin >> day;
cin >> year;
}
43
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
44
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
return result;
}
Instructor Notes: Add the following code to the solution of the previous
program project.
45
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
2. Outline of Topics
5.1 void-Functions
Definitions of void Functions
return Statements in void Functions
5.2 Call-by-Reference Parameters
A First View of Call-by-Reference
Call-by-Reference in Detail
Mixed Parameter Lists
5.3 Using Procedural Abstraction
Functions Calling Functions
Preconditions and Postconditions
5.4 Testing and Debugging Functions
Stubs and Drivers
46
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
Read the sections 7.2 and 7.4 of Ellis and Stroustrup, The Annotated C++ Reference
Manual, Addison Wesley, 1991, reprinted with corrections 1994, ISBN 0-201-5149-1, and
sections 11.3.1-11.3.3 in Stroustrup, The design and Evolution of C++ Addison Wesley,
1994 reprinted with corrections, May 1994, or Stroustrup, The C++ Programming
Language, 3rd edition Addison Wesley Longman, 1997. for details.
2
“automagically” is a neologism which means automatically, as if by magic.
47
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
parameter (i.e. argument) is fetched. When an assignment needs to be made, the value to
be assigned is stored into the memory at the address of the caller's actual parameter. (See
the discussion in the text in the section “Call-by-Reference in Detail” of this chapter.) I
find that even with fairly weak students a discussion as the summary presented here along
with the text's discussion results in a good understanding of these concepts.
Notice that the syntactic distinction between call-by-reference and call-by-value is the
ampersand sign, &, which is between the type-name and the parameter namein the
parameter list. This distinction allows us to mix value and reference parameter passing
mechanisms. There is no C++ reason for placing the ampersand adjacent to the type, but
this is typically C++ programming style, found in most C++ texts and treatises.
It is important to note that the ampersand for a reference parameter must be put both into
the declaration (prototype) and into the definition of a function using pass-by-reference.
One further warning: overloading based on a distinction between a reference parameter and
a value parameter was not supported in many early compilers. This has been corrected in
more recent compilers. GNU g++ complains about the following code.
//file: test1.cc
//to check overloading based on distinction between
//value parameter and reference parameter of same type.
#include <iostream>
using namespace std;
void f( int &i, int j) { cout << "f(int&, int)" << endl; }
void f( int i, int& j){ cout << "f(int, int&)" << endl; }
int main()
{
int i = 1, j = 2;
48
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
f(i, 1);
f(1, j);
f(1, 1);
f(i, j);
return 0;
}
The error messages are:
test1.cc: In function `int main()':
test1.cc:15: call of overloaded `f (int, int)' is ambiguous
test1.cc:7: candidates are: void f(int &, int) <near match>
test1.cc:8: void f(int, int &) <near match>
test1.cc:16: call of overloaded `f (int &, int &)' is
ambiguous
test1.cc:7: candidates are: void f(int &, int)
test1.cc:8: void f(int, int &)
It should be reiterated that omission of an ampersand & for a variable that should be a
reference-parameter is a an error that can be quite difficult to find.
49
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
1) having no abnormal termination of the program for data that meets the preconditions on
the input, that is, the program should run to a normal successful completion for correct
data, and
2) for correct input, the program should generate correct output - output that meets the post
conditions for that input data.
3) desirable behavior in response to incorrect data is that the program should behave in a
reasonable way. This may mean summary termination in the face of error, or detecting
errors and giving the user another chance, or behaving in some other fail-safe way (an
elevator control, perhaps?)
The pre- and post- conditions should be machine testable. Accomplishing this can be
difficult in some instances. This is a goal to be sought in writing pre- and post- conditions.
Failure to meet this goal means increased difficulty in demonstrating that the program is
correct.
How?
The main program can be written, then tested independently of the subprograms by
writing 'stub' subprograms - small subprograms that do little more than return fictitious
data that the calling function needs to be able to continue, and (at least in my
programming) emits a message that lets the tester know that the subprogram has been
encountered. These stub subprograms should simple enough that correctness is not a
problem.
This technique allows part of a program to be tested before the rest of it has been tested, or
perhaps before the subprograms have been written.
50
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 5
The other technique is bottom up: test the functions independently of the calling program.
How? Write a driver - a main program or calling program substitute - that exercises the
subprogram with data that a correct calling program might present to the subprogram
during execution. In fact, incorrect data should also be used to test the robustness of the
subprogram. Proper selection of data is essential to the success of this testing technique.
These testing techniques are useful to the extent that the client program author and the
subprogram program author use procedural abstraction. This means that the specifications
of the subprogram is all that is known to the client, and, beyond the specifications, any use
to which the subprogram in put is not known to the subprogram author.
Dividing a program into separate pieces, which are tested apart from each other, is a useful
technique independently of pre and post- conditions. However, the testing is limited if
exact conditions are not known. Clearly, a specification of input, output and action for all
functions is essential to the ability to full use of this testing technique.
51
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley