Professional Documents
Culture Documents
Problem Solving with C++ 9th Edition Savitch Solutions Manual instant download all chapter
Problem Solving with C++ 9th Edition Savitch Solutions Manual instant download all chapter
https://testbankdeal.com/product/problem-solving-with-c-9th-
edition-savitch-test-bank/
https://testbankdeal.com/product/problem-solving-with-c-10th-
edition-savitch-solutions-manual/
https://testbankdeal.com/product/problem-solving-with-c-10th-
edition-savitch-test-bank/
https://testbankdeal.com/product/engineering-problem-solving-
with-c-4th-edition-etter-solutions-manual/
Engineering Problem Solving With C++ 4th Edition Etter
Test Bank
https://testbankdeal.com/product/engineering-problem-solving-
with-c-4th-edition-etter-test-bank/
https://testbankdeal.com/product/data-abstraction-and-problem-
solving-with-c-walls-and-mirrors-6th-edition-carrano-solutions-
manual/
https://testbankdeal.com/product/data-abstraction-and-problem-
solving-with-c-walls-and-mirrors-7th-edition-carrano-solutions-
manual/
https://testbankdeal.com/product/data-abstraction-and-problem-
solving-with-c-walls-and-mirrors-6th-edition-carrano-test-bank/
https://testbankdeal.com/product/data-abstraction-and-problem-
solving-with-c-walls-and-mirrors-7th-edition-carrano-test-bank/
Chapter 7
ARRAYS
Regarding the solutions presented here.: C++ leaves many options on how to do a problem,
and any book will necessarily choose a subset to present. It is necessary to read the text, as
that is what the student has to work with. I am striving to produce a complementary
document to the text, a document for the instructor. Most of the time, will use the
initialization list style for constructors. If you present the code using the initializer list, you
should also assign Appendix 7 on constructor initialization.
Here, I have done the interactive version only. The solution is broken into two files. The
source for each is listed, along with test data, command generating the output and the
output.
I have done the solution using structs here. The enhancement of adding the choice of
graphical output is provided. I have done only the interactive version here. The variation
using file i/o is left to the reader. Notes will be supplied for doing this without the struct.
//Program is to
//1)read in long term month by month average rain fall
// averages
//2)read in the previous year's month by month actual rain
// fall.
1
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//Output:
//'nicely' formatted table showing rainfall for each of the
// previous
//12 months as well as how much above or below the monthly
// average the rainfall is for each month. The output
// should correctly label months.
//
//Month name handling: code months as integers and do a
//conversion at output. Any input scheme acceptable as long
//as the user interface is relatively easy to use.
//Enhanced version:
//Add capability to print two bar graphs for each month,
//showing the average rainfall and the actual rainfall for
//each of the previous 12 months. Ask the user's preference:
//a table or a graph, and display the format requested.
//
//Provide a loop to repeat the process at the user's request.
#include <iostream>
#include <cstring>
2
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <cstdlib>
struct monthly_rain
{
int month;
double rain_fall;
double avg_rain_fall;
};
3
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
using namespace std;
int current_month;
monthly_rain rainfall[12];
char ans;
char tg;
do
{
input( rainfall, current_month);
cout << "Please choose between g)raphical and t)abular "
<< "output" << endl;
cin >> tg; //tg means table/graphics choice :)
if ( 't' == tg || 'T' == tg )
{
cout << "You chose the tabular output." << endl;
output_table( rainfall, current_month );
}
else if ( 'g' == tg || 'G' == tg )
{
cout << "You chose the graphical output" << endl;
output_bargraph( rainfall, current_month);
}
else
{
cout << "You typed neither of the choices. "
4
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
void full_month_name(int);
5
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
rainfall[i].month = i;
cout << endl;
}
cout << endl << "The actual rainfall: " << endl;
cout << "What is the current month? Please give the "
<< "number of the month (Jan = 0, etc." << endl;
6
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
cout << "For month ";
full_month_name(i);
cout << ' ';
cin >> rainfall[i].rain_fall;
cout << "\tRainfall: " << rainfall[i].rain_fall;
cout << endl;
}
7
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
8
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
cout.width(4);
cout << rainfall[i].avg_rain_fall << " |";
}
cout.width(4);
cout << rainfall[i].avg_rain_fall << endl;
9
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
case 0: cout << "Jan";
break;
case 1: cout << "Feb";
break;
case 2: cout << "Mar";
break;
case 3: cout << "Apr";
break;
case 4: cout << "May";
break;
case 5: cout << "Jun";
break;
case 6: cout << "Jul";
break;
case 7: cout << "Aug";
break;
case 8: cout << "Sep";
break;
case 9: cout << "Oct";
break;
case 10: cout << "Nov";
break;
case 11: cout << "Dec";
break;
default: cout << "NO SUCH MONTH " << month << endl;
exit(1);
}
}
10
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
11
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
default: cout << "NO SUCH MONTH " << month << endl;
exit(1);
}
}
//file: Ch7Prg1.bargraph.cpp
//
//to print two bargraphs for each month, showing average and
//actual rainfall each month.
#include <iostream>
struct monthly_rain
{
int month;
double rain_fall;
double avg_rain_fall;
};
12
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
13
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
full_month_name( i );
if ( i >= current_month )
cout << "(Previous year)";
cout << "\naverage\t ";
bargraph( rainfall[i].avg_rain_fall );
cout << "\nactual\t ";
bargraph( rainfall[i].rain_fall );
cout << endl;
if ( 5 == i )
{
output_scale();
}
}
output_scale();
}
The rainfall averages in the data come from The World Almanac and Book of Facts 1993,
published by the World Almanac. (C) Phaos Books,1992. The rainfall numbers presented
here are made-up.
$cat data
3.7 3.6 5.1 3.8 4.2 4.2 4.4 4.8 4.0 3.3 3.3 3.5
4
4.3 3.2 5.5 5.1 4.0 2.2 2.0 1.1 4.1 3.3 3.9 3.7
t
y
3.7 3.6 5.1 3.8 4.2 4.2 4.4 4.8 4.0 3.3 3.3 3.5
14
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
4
4.3 3.2 5.5 5.1 4.0 2.2 2.0 1.1 4.1 3.3 3.9 3.7
g
y
3.7 3.6 5.1 3.8 4.2 4.2 4.4 4.8 4.0 3.3 3.3 3.5
4
4.3 3.2 5.5 5.1 4.0 2.2 2.0 1.1 4.1 3.3 3.9 3.7
h
n
The command used to run the program and the output is:
17:19:43:~/AW$ a.out < data > ch7prb2.out
There follows edited output obtained from this run. I have 'redacted' the input and the
output where either is identical for all three runs and after it has been seen.
$cat ch7prb2.out
Monthly rainfall input routine.
15
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
What is the current month? Please give the number of the month (Jan = 0,
etc.
The current month is: May
Please enter the actual rainfall for each month, as prompted, First for
the
months in the previous year:
For month May Rainfall: 4.3
For month June Rainfall: 3.2
For month July Rainfall: 5.5
For month August Rainfall: 5.1
For month September Rainfall: 4
For month October Rainfall: 2.2
For month November Rainfall: 2
For month December Rainfall: 1.1
Now for the months in this year:
For month January Rainfall: 4.1
For month February Rainfall: 3.3
For month March Rainfall: 3.9
For month April Rainfall: 3.7
Please choose between g)raphical and t)abular output
You chose the tabular output.
Monthly Rainfall
For the 12 Months Preceding May
Actual, Average, and Difference (= Actual - Average)
-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----
Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----
average 4.1 | 3.3 | 3.9 | 3.7 | 4.3 | 3.2 | 5.5 | 5.1 | 4.0 | 2.2 | 2.0 | 1.1
actual 3.7 | 3.6 | 5.1 | 3.8 | 4.2 | 4.2 | 4.4 | 4.8 | 4.0 | 3.3 | 3.3 | 3.5
diffs 0.4 |-0.3 |-1.2 |-0.1 | 0.1 |-1.0 | 1.1 | 0.3 | 0.0 |-1.1 |-1.3 |-2.4
P)rev yr | | | | P | P | P | P | P | P | P | P
16
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
Average rainfall:
For month January Avg Rainfall: 3.7
. . . .
For month December Avg Rainfall: 3.5
Rainfall 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5
|****|****|****|****|****|****|****|****|****|****|****|****|****|****
January
average **************************************
actual *****************************************
February
average *************************************
actual *********************************
March
average ***************************************************
actual ***************************************
April
average **************************************
actual **************************************
May (Previous year)
average *******************************************
17
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
actual *******************************************
June (Previous year)
average *******************************************
actual *********************************
Rainfall 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5
|****|****|****|****|****|****|****|****|****|****|****|****|****|****
July (Previous year)
average *********************************************
actual *******************************************************
August (Previous year)
average ************************************************
actual ***************************************************
September(Previous year)
average ****************************************
actual ****************************************
October (Previous year)
average *********************************
actual ***********************
November(Previous year)
average *********************************
actual ********************
December(Previous year)
average ***********************************
actual ************
Rainfall 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5
|****|****|****|****|****|****|****|****|****|****|****|****|****|****
Y/y continues, any thing else quits
Monthly rainfall input routine.
. . . .
18
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
. . . .
Rainfall 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5
|****|****|****|****|****|****|****|****|****|****|****|****|****|****
January
average **************************************
actual *****************************************
. . . .
April
average **************************************
actual **************************************
May (Previous year)
average *******************************************
actual *******************************************
. . . .
19
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
December(Previous year)
average ***********************************
actual ************
Rainfall 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5
|****|****|****|****|****|****|****|****|****|****|****|****|****|****
Y/y continues, any thing else quits
Much of the program with structs will be identical to the version without. This makes
transforming one into the other easy. This is particularly true when we are moving from
using structs to not using structs.
int month;
double rain_fall[12];
double avg_rain_fall[12];
Pass these to each function called from main, and modify each function to access these
rather than the structure, for example, the input routine would have declaration:
and the two output routines would have the same sort of declaration:
20
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int current_month );
The changes necessary internal to the routines is illustrated here. We replace this following
loop from the input routine,
with this:
21
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//
// If the sum can be contained in 10 digits, output the sum
// otherwise output an indication of overflow error.
//
// Provide a loop to repeat the action until user wants to end program.
//
// Note on overflow detection. Overflow occurs when the carry bits into
// and out of the highest digit are both set. This condition is is
// equivalent to the text's "when the result will not fit in 10
hexadecimal
// digits", and is easy to test.
//
// My solution requires that the Hex digits A-F be entered upper case.
// A nice enhancement would be to allow either case.
//
// Finally, debugging this was a bear. I have left a some of my test
// code (but by no means all) for (what I hope will be) the student's
// edification.
//
// Be certain that the student tests the program with single digit, two
// digit and with all numbers of data all the way to 10 hex digits, in
all
// combinations in each of the two input positions, and test with short
// data before and after many digit data and conversely.
//
#include <iostream>
int i = 0;
char c = '0';
while(c != 'q')
{
cin >> c;
num[i] = c;
i++;
}
num[--i] = '0';
// cout << "num[" << i << "] is " << num[i] << endl << endl;
// i is the of the last number entered
// reverse segment [0, i), that is 0<= k < i
// to put the least significant digit in the
22
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
// index 0 position.
char tmp;
for(int k = 0; k < i/2; k++)
{
tmp = num[k];
num[k] = num[i-1-k ];
num[i-1-k]=tmp;
}
}
23
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
carry = nextCarry;
s = (x + y + carry)%16; // digit value
// cout << "s " << s << endl;
int main()
{
using std::cout;
using std::cin;
using std::endl;
input(num1);
cout << endl;
output(num1);
cout << endl;
input(num2);
cout << endl;
output(num2);
24
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
return 0;
}
/*
FEDCBA9876q
123456789Aq
y
CEDCBA9876q
123456789Aq
y
DEDCBA9876q
123456789Aq
n
FEDCBA9876
Enter a hexadecimal number of 10 or fewer hex digits
Hex digits are 0-9A-F Code requires uppercase A through F
Press lower case q to stop entry of the hex digits
123456789A
25
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
FEDCBA9876
+123456789A
------------
1111111110
y continues
CEDCBA9876
Enter a hexadecimal number of 10 or fewer hex digits
Hex digits are 0-9A-F Code requires uppercase A through F
Press lower case q to stop entry of the hex digits
123456789A
CEDCBA9876
+123456789A
------------
E111111110
y continues
DEDCBA9876
Enter a hexadecimal number of 10 or fewer hex digits
Hex digits are 0-9A-F Code requires uppercase A through F
Press lower case q to stop entry of the hex digits
123456789A
DEDCBA9876
+123456789A
------------
F111111110
y continues
*/
26
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
int main()
{
using namespace std;
char array[81]
= "mary had a little lamb. its fleece was white as snow.";
cout << array << endl;
int size;
size = length(array);
cout << "size = " << size << endl;
char array1[81]
="Now is the time for all good men to come to the aid of the country.";
27
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
A test run:
22:24:31:~/AW$ a.out
mary had a little lamb. its fleece was white as snow.
size = 53
reduced array = mary hdliteb.sfwno
28
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double s[MAX_SIZE];
double stdDeviation, avg;
29
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
char ans;
do
{
cout << "Enter " << MAX_SIZE << " values, separated by\n"
<< " white space, Terminated each with <cr>. \n"
<< "I will compute the standard deviation.\n";
return 0;
}
30
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
I emphasize strongly that divide and conquer is the secret to successful programming,
regardless of the paradigm. This is why object oriented programming, object based
programming, and procedure oriented programming are effective. Each of these techniques
has its collection of problems for which that particular technique works best. The idea that
is common to these techniques on is the encapsulation of commonalties, the separation of
issues, and the hiding of detail.
31
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
#include <cstdlib>
#include <cctype>
32
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
using namespace std;
Large_integer first, second, sum;
cout << "Large integer summing program " << endl;
cout << "Please enter an integer, 20 digits or less "
<< endl;
input( first );
cout << "you entered " << endl;
output (first);
cout << endl;
cout << "Enter another integer, 20 digits or less" << endl;
input( second );
cout << "you entered " << endl;
output (second); cout << endl << endl;
33
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//Reverse array
34
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
35
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
larger_size = first.size;
}
else
{
for( int i = first.size; i < second.size; i++)
first.digit[i] = 0;
larger_size = second.size;
}
36
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
}
else //the result is legal.
{
sum.digit[larger_size] = carry;
sum.size = larger_size + 1;
}
}
else //no carry, no problem
sum.size = larger_size;
}
$:~/AW$ a.out
Large integer summing program
Please enter an integer, 20 digits or less
2345676543456312987
you entered
2345676543456312987
Enter another integer, 20 digits or less
432256456785678689
you entered
432256456785678689
37
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
15:28:49:~/AW$ a.out
Large integer summing program
Please enter an integer, 20 digits or less
9898987656545434334445546
Input number size too large. Aborting.
15:28:57:~/AW$
15:29:22:~/AW$ a.out
Large integer summing program
Please enter an integer, 20 digits or less
98765432101234567890
you entered
98765432101234567890
Enter another integer, 20 digits or less
234567890987654321123
Input number size too large. Aborting.
15:31:49:~/AW$a.out
Large integer summing program
Please enter an integer, 20 digits or less
98765432109876543210
you entered
38
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
98765432109876543210
Enter another integer, 20 digits or less
56789012345678901234
you entered
56789012345678901234
It took about 15 minutes to convert from the struct solution to this non-struct solution. A
reason why the conversion is easy is the structure (pun intended) imposed on the
programming by the use of the struct to relay the information to and from the functions.
Going the other direction is harder.
I changed the functions declarations (prototypes) to eliminate the struct, then I changed the
main program to agree with the function declarations (prototypes). Then the code in the
input, output, and add functions had to be changed. This amounted to doing a query-replace
of .digit by the empty string, and replacing first.size, second.size, sum.size, number.size
with the . replaced by an underscore.
The result compiles and runs with exactly the same user interface.
39
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//
//Input: digits of two integers
// It appears that a "partially filled array structure"
//from the text will be of value here.
//Output: the sum of the two large integers is written to the
//screen
//
//algorithm: computer version of the traditional paper and
// pencil algorithm.
#include <iostream>
#include <cstdlib>
#include <cctype>
40
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
//Design decision: lower indices correspond
//to lower order digits
using namespace std;
int first[MAX_DIGITS+1];
int first_size; //number of digits first_sizE
int second[MAX_DIGITS +1];
int second_size;
int sum[MAX_DIGITS +1];
int sum_size;
41
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
42
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
number_size++;
i++;
cin.get(ch);
}
//Reverse array
for ( int k = 0; k < number_size/2; k++ )
{
int temp = number[k];
number[ k ] = number[ number_size - 1 - k ];
number[ number_size - 1 - k ] = temp;
}
}
43
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
44
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
carry = 1;
sum[i] = sum[i] - 10;
}
else
carry = 0;
}
if ( 1 == carry )
{
if( larger_size == 20) //the carry is out of digit 20
{
cout << "An overflow has occurred. "
<< "Result is set to 0" << endl;
sum_size = 1;
sum[0] = 0;
}
else //the result is legal.
{
sum[larger_size] = carry;
sum_size = larger_size + 1;
}
}
else //no carry, no problem
sum_size = larger_size;
}
45
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
Students should NOT ATTEMPT to do TOO MUCH in any one function! This leads to
code that is impossible to understand, even for the author of the code. There will be no end
of trouble debugging such code.
Urge the students to get one function running first. I usually try to get main running with
stubs, but debugging functions with drivers helps. Then the student should try to get the
whole program running by adding functions to the main one at a time.
This pays off when the programmer discovers that a design error has been made. The
principle of doing a small number of connected things in a function tends to confine the
necessary repairs to one or at most a very few modules, functions, or class member
functions.
46
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
#include <cassert>
#include <cctype>
struct char_freq
{
char ch;
int count;
};
47
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
char_freq list[50] ={0,0}; //we are going to pick up
//punctuation, etc.
int list_size = 0;
input( list, list_size );
sort( list, list_size );
output( list, list_size);
return 0;
}
48
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
49
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
list[size].count=1;
list[size].ch = c;
size ++;
assert( size <= 26);
}
50
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
A data file
51
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
d 6
c 2
u 2
y 3
, 1
b 1
k 1
p 1
21:55:15:~/AW$
Here is some output after the sort routine was modified for use here. See that file for some
suggestions on how to modify it.
23:44:52:~/AW$ a.out
Mary had a little lamb Its fleece was white as snow.
Letter: Number of Occurrences.
a 6
e 5
s 5
l 4
t 4
w 3
i 2
h 2
m 2
y 1
b 1
I 1
r 1
f 1
d 1
52
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
n 1
o 1
//Programming note:
//I made a design error that I did not discover until the program
//was in final testing. Because the problem had been written using
//the principle "one function does one thing", the changes needed
//were confined to just a few functions.
53
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//
//I had used a char for the face value, using 2 - 9 and the 't'
//'j' 'q' 'k' and 'a' for ten through ace. For test data that was
//a digit, the sort routine for the struct from an earlier problem
//(modified to sort small to large) worked fine. Once a test was
//made using any of the "face cards" ten, jack, queen, king, ace.
//It was found that the sort routine worked. BUT NOT correctly.
//In this problem, ten < jack < queen < king < ace. BUT the
//order using the ASCII encoding is 'a' < 'k' < 'q' < 't'
//which is not at all what we need. The use of the enum for the
//face value of the card with the few changes this necessitated
//was the necessary repair. This should be no problem for the
//student, since the enum is dealt with in the text with
//considerable care in Chapter 3, page 354 and following.
//If you have not done the enum data type, I have presented, but
//have commented out, declarations that can be used to side step
//this problem, and have added (also commented out) const int
//declarations for the enum constants along with suggestions for
//replacing the three enum tags with int.
#include <iostream>
#include <cstdlib>
#include <cctype>
54
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//If you have not done enums, the following declarations enable
//this code to run correctly without the enum declarations. You
//may wish to do a global search and replace instead of using
//these typedef statements, since typedef has not yet been
//treated in the text. There is a short discussion of typedef
//in the text. See the box, Type Definitions.
//typedef int Card_suite;
//typedef int Face_Value;
//typedef int Hand_Value;
//const int NOTHING =0 , ONE_PAIR= 1, TWO_PAIRS=3,
// THREE_OF_KIND=4, STRAIGHT=5, FLUSH=6,FULL_HOUSE=7,
// FOUR_OF_KIND=8, STRAIGHT_FLUSH=9;
//const int CLUBS=0, DIAMONDS=1, HEARTS=2, SPADES=3;
//const int TWO=0 , THREE=1, FOUR=2, FIVE=3, SIX=4, SEVEN=5,
55
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
struct Card
{
Card_Suite suite;
Face_Value face;
};
56
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
57
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
58
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
using namespace std;
char ans;
Card hand[5];
cout << "Poker Hand Evaluation Program - " << endl
<< "Please Enter a 5 card poker hand, "
<<"I'll evaluate this "
<< "hand as one of " << endl
<< "NOTHING, ONE_PAIR, TWO_PAIRS, THREE_OF_KIND, "
<< "STRAIGHT FLUSH, FULL_HOUSE" << endl
<< "FOUR_OF_KIND, or STRAIGHT_FLUSH" << endl << endl
<< "Encode Clubs as c, Diamonds as d, Hearts as h, "
<< " Spades as s" << endl
<< "Enter the value as 2-9, t, j, q, k a, "
<< " Upper case OK " << endl << endl;
do
{
input ( hand );
cout << "\nSorted hand is: " << endl;
output_hand( hand );
cout << "value of hand is: " ;
report_hand_value( hand );
59
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
60
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
61
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
return THREE_OF_KIND;
else if ( has_two_pair(hand) )
return TWO_PAIRS;
else if ( has_one_pair(hand) )
return ONE_PAIR;
else return NOTHING;
}
62
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
63
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
break;
case SIX: cout << 6;
break;
case SEVEN: cout << 7;
break;
case EIGHT: cout << 8;
break;
case NINE: cout << 9;
break;
case TEN: cout << 10;
break;
case JACK: cout << "Jack";
break;
case QUEEN: cout << "Queen";
break;
case KING: cout << "King";
break;
case ACE: cout << "Ace";
break;
default: cout << "Bad card face Aborting";
exit(2);
}
}
64
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
char suite;
Face_Value face;
for( int i = 0; i <= 4; i++)
{
cout << "Card " << i+1 << " suite: ";
cin >> suite;
cout << " " << "suite entered: " << suite << " " ;
cout << ", face: " ;
get_face( face );
cout << " face entered: ";
put_face( face );
cout << endl;
suite = tolower( suite );
hand[i].face = face;
switch ( suite )
{
case 'c': hand[i].suite = Card_Suite(0);
break;
case 'd': hand[i].suite = Card_Suite(1);
break;
case 'h': hand[i].suite = Card_Suite(2);
break;
case 's': hand[i].suite = Card_Suite(3);
break;
default: cout << "bad suite, aborting" << endl;
exit(1);
}
}
65
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
sort_hand( hand, 5 );
}
if(hand[0].face + 1 == hand[1].face
&& hand[0].face + 2 == hand[2].face
&& hand[0].face + 3 == hand[3].face
&& hand[0].face + 4 == hand[4].face )
return 1;
else
return 0;
}
66
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
if(hand[0].face == hand[1].face
&&hand[1].face == hand[2].face
&&hand[2].face == hand[3].face
||
hand[1].face == hand[2].face
&&hand[2].face == hand[3].face
&&hand[3].face == hand[4].face )
return 1;
else
return 0;
}
if(hand[0].face == hand[1].face
&&hand[1].face == hand[2].face
||
hand[1].face == hand[2].face
67
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
&&hand[2].face == hand[3].face
||
hand[2].face == hand[3].face
&&hand[3].face == hand[4].face )
return 1;
else
return 0;
}
//Precondition:
//Postcondition:
//if the two cards other than the three of a kind are equal,
// return true
//else
// return false
if(hand[0].face == hand[1].face
&&hand[1].face == hand[2].face
&&hand[3].face == hand[4].face
||
hand[0].face == hand[1].face
&&hand[2].face == hand[3].face
&&hand[3].face == hand[4].face )
68
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
return 1;
else
return 0;
}
69
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
if ( hand[0].face == hand[1].face ||
hand[1].face == hand[2].face ||
hand[3].face == hand[4].face )
return 1;
else
return 0;
}
70
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
put_face( hand[i].face );
cout << endl;
}
}
//File: sort_hand.cpp
//
//Most of the changes were made with a query-search command.
//
#include <iostream.h>
struct Card
{
Card_Suite suite;
Face_Value face;
};
71
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
index_of_next_smallest =
index_of_smallest(a, index, number_used);
swap_values(a[index], a[index_of_next_smallest]);
//a[0] <= a[1] <=...<= a[index] are smallest of original
//array elements. The rest of the elements are in the
//remaining positions.
}
}
72
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
I am including more test data than for some other problems since I discovered errors in my
code with many of these cases. In the interest of space, I am presenting only part of the output.
73
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
c k c 9 c t c j s 2
y
c 5 s a c 2 d 2 c 4
y
s 3 c k c 2 d 2 h 3
y
c t s 3 s t d t c 4
y
s k c 9 s j c q d t
y
c 2 c 8 c 7 c 3 c 5
y
h 3 s 3 c 2 d 2 c 3
y
h q c a d q c q s q
y
s a s q s k s t s j
n
A command that runs the program after compilation, with the above data.
Note that the output is a little nicer than the interactive run:
74
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
75
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
. . .
76
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
This program is to ask for moves alternately from players X and O. The display should be
board-like:
77
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
1 2 3
4 5 6
7 8 9
The players enter their moves by entering a number corresponding to the place to be
marked. After each move, the program displays the changed board. After several moves the
board may appear:
X X O
4 5 6
O 8 9
Planning:
Input,
Play
Output
This can be done with a simple one dimension array to hold the game, a play function, a
display function and a scoring function, which can be called by the play function.
The way I approached this is to have a Game class. This class has a constructor and a
play member having a char parameter, 'X' and 'O' for permissible arguments. The
class has private functions score() and display(), and a char array as a data
member.
Main declares game to be a Game object, and calls game_play(). The game_play()
function alternately calls play('X') and play('O'), the function play prompts
players for input, modifies the data in array, calls display_array(), then runs the
score() member which returns 'X' if player X wins, 'O' if player O wins, 'T' for tie,
or '\0' (NULL) for no winners.
78
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
There is one additional wrinkle that is not covered in the text, but works on all systems
having a standard C/C++ library. The library call int system( char [] str )
function executes any shell command the user puts into its argument.
(A shell command is any command you use to do something at the system's prompt, $,
such as dir, ls, clear or cls, etc.)
Here I use system("clear") since most Unix systems respond to that by clearing the
screen and placing the cursor in the upper left hand position of the screen. If you are using
Windows you should use system("clear"), since the DOS command to clear the
screen is "clear".
Take care not to allow the overwriting of a position already occupied by an opponent with
one of your own. This again points out the necessity for complete testing. I finished this
problem and would have left it, were it not for my accidentally using a cell that was
already occupied. It worked. I fixed that with a loop that required the location being used
to still have a digit in it.
Take care to make your program robust. I found and fixed a couple of loops in my code
that bad input caused to go infinite.
// ********************************************************************
//
// This program plays tic-tac-toe using a 1D array to represent
// the board.
// It does not check for a win, only an end of game.
// ********************************************************************
#include <iostream>
// Prototype
void showBoard(char board[]);
79
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
// ====================
// main function
// ====================
int main()
{
char board[9]; // Holds digits, X, or O
int i;
int numMoves = 0; // Number of moves
char whoseTurn = 'X'; // Current player's move
int move;
80
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
else
whoseTurn = 'X';
numMoves++;
}
}
}
showBoard(board);
cout << endl << "Game over!" << endl;
return 0;
81
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
#include <cstdlib>
#include <cstddef>
Seating seatAssignment;
int main()
{
using std::cout;
using std::cin;
using std::endl;
Seating plan;
int row;
char seat;
int seatNo;
int r;
int s;
// Display seats
for(r = 1; r < NO_ROWS; r++)
{
for (s = 0; s < 4; s++)
{
cout << plan[r][s] << " ";
if(s == 1 )
cout << " ";
82
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
}
cout << endl;
}
cout << "Please enter your requst in the form \"3 C\" for Row 3, Seat
C\n"
<< "There are " << NO_ROWS << " rows. Seats are A, B, C, D.\n";
cin >> row >> seat;
seatNo = seat - 'A';
if('X' != plan[row][seatNo])
plan[row][seatNo] = 'X';
else
cout << "****That seat is taken****.\n****No assignment
made****.\n"
<< "****Please make another request****\n";
return 0;
}
/*
Typical run
Savitch Airlines
Seat Reservation Program.
Reserved seats are marked 'X'. Others are available.
A B C D
83
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
A B C D
A B C D
A B C D
A B C D
A B C D
Savitch Airlines
Seat Reservation Program.
Reserved seats are marked 'X'. Others are available.
Please enter your requst in the form "3 C" for Row 3, Seat C
There are 7 rows. Seats are A, B, C, D.
3D
A B C D
A B C D
A B C X
A B C D
A B C D
A B C D
N or n quits, anyting else continues
y
Savitch Airlines
Seat Reservation Program.
Reserved seats are marked 'X'. Others are available.
Please enter your requst in the form "3 C" for Row 3, Seat C
There are 7 rows. Seats are A, B, C, D.
3D
****That seat is taken****.
****No assignment made****.
****Please make another request****
A B C D
A B C D
A B C X
A B C D
A B C D
A B C D
N or n quits, anyting else continues
n
Press any key to continue
*/
#include <iostream>
84
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <fstream>
#include <cstdlib>
// ======================
// main function
// ======================
int main()
{
string targetName; // Target name
string boyName, girlName; // Temp boy/girl name
int popularity; // Temp popularity
string boyNames[NUMNAMES]; // Array of boy names
string girlNames[NUMNAMES]; // Array of girl names
int boyPopularity, girlPopularity; // Popularity of match
ifstream in_stream;
int i;
// First load the names from the file into the arrays.
// Assumes the file "babynames2004.txt" is in the current directory
in_stream.open("babynames2004.txt");
if (in_stream.fail())
{
cout << "Input file opening failed." << endl;
exit(-1);
}
// Read each name from the file along with the popularity
for (i=0; i < NUMNAMES; i++)
{
// Input popularity, boy name, and girl name
in_stream >> popularity >> boyName >> girlName;
// Store in array
boyNames[i] = boyName;
girlNames[i] = girlName;
}
in_stream.close();
85
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
if (boyNames[i] == targetName)
{
boyPopularity = i+1;
}
if (girlNames[i] == targetName)
{
girlPopularity = i+1;
}
}
// Output results
cout << targetName << " is ";
if (boyPopularity > 0)
{
cout << "ranked " << boyPopularity << " in popularity among
boys.\n";
}
else
{
cout << "not ranked among the top 1000 boy names.\n";
}
cout << targetName << " is ";
if (girlPopularity > 0)
{
cout << "ranked " << girlPopularity << " in popularity among
girls.\n";
}
else
{
cout << "not ranked among the top 1000 girl names.\n";
}
return 0;
}
Programmign Project 15: Draw Bar chart with SVG File format and arrays
// **********************************************************************
//
// This program draws a bar chart using the SVG file format.
// It uses an input array with value of -1 to signal the end of
// values to graph. It supports up to 100 entries.
//
//
***********************************************************************
#include <iostream>
#include <fstream>
#include <cstdlib>
86
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
// Function prototypes
int findMax(const int a[]);
void saveSVG(int a[]);
// ======================
// findMax:
// Scans through the array and returns
// the largest value in the array.
// ======================
int findMax(const int a[])
{
int i, biggestBar, curValue;
i = 0;
curValue = 0;
biggestBar = -1;
while ((curValue != -1) && (i < MAXSIZE))
{
curValue = a[i];
if (curValue > biggestBar)
{
biggestBar = a[i];
}
i++;
}
return biggestBar;
}
// ======================
// saveSVG:
// Saves the graph as an SVG file.
// ======================
void saveSVG(int bars[])
{
int i;
ofstream out_stream;
int biggestBar;
double scale;
87
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
out_stream.open("Ch7Proj15.svg");
if (out_stream.fail())
{
cout << "Output file opening failed." << endl;
exit(-1);
}
// Output "boilerplate" for SVG files
out_stream << "<?xml version=\"1.0\" standalone=\"no\"?>" << endl;
out_stream << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"" <<
endl;
out_stream <<
"\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> " << endl;
out_stream << "<svg width=\"500\" height=\"500\"
xmlns=\"http://www.w3.org/2000/svg\">" << endl;
// Draw axis
out_stream << "<line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"" <<
MAXHEIGHT-1 << "\" " << endl;
out_stream << "style=\"stroke:purple;stroke-width:2\"/>" << endl;
out_stream << "<line x1=\"0\" y1=\"" << MAXHEIGHT-1 << "\" x2=\""
<< MAXHEIGHT-1 << "\" y2=\"" << MAXHEIGHT-1 << "\" " << endl;
out_stream << "style=\"stroke:purple;stroke-width:2\"/>" << endl;
// ======================
// main function
// ======================
int main()
{
int bars[MAXSIZE]; // Values for bar chart
int i = 0, temp = 0;
88
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
return 0;
}
// ****************************************************************
//
// This program implements a memory matching game.
//
// It uses a 2D array to store the cards (pairs of numbers 1-8)
// and randomly shuffles them through repeated swaps. It uses a
// second 2D array to record whether or not a card is face up or
// face down.
//
// ****************************************************************
#include <iostream>
#include <cstdlib>
// Function prototypes
void InitializeCards(int cards[][LENGTH]);
void ShowCards(int cards[][LENGTH], bool faceup[][LENGTH]);
// ======================
// InitializeCards
// Places pairs of numbers in the 2D array and then
// randomly shuffles them.
// ======================
void InitializeCards(int cards[][LENGTH])
{
int x1,y1,x2,y2;
int i;
89
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int temp;
// ======================
// ShowCards
// Generates a display on the screen. If faceup=false,
// an * is output, otherwise the card in that slot is output.
// ======================
void ShowCards(int cards[][LENGTH], bool faceup[][LENGTH])
{
int x,y;
90
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
// ======================
// main function
// ======================
int main()
{
// Variable declarations
int cards[LENGTH][LENGTH];
bool faceup[LENGTH][LENGTH];
int x,y, temp;
int x1,y1,x2,y2;
int pairsleft = 8;
cout << "Find all the matching pairs on the board." << endl;
91
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
#include <iostream>
// Make constants for the number of slots each day and the number
// of days. (Such constants may be particularly useful in cases
// where we have functions that take 2-dimensional arrays as arguments,
// as a constant used in the function header will convey information
// about the order of the dimensions.)
const int NUM_SLOTS = 4;
const int NUM_DAYS = 4;
// Constants for the values that we will store in the int[][] arrays
92
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
using namespace std;
jeff[0][0] = jeff[0][3]
= jeff[1][0] = jeff[1][1] = jeff[1][2] = jeff[1][3]
= jeff[2][1] = jeff[2][2] = jeff[2][3]
= jeff[3][1]
= SLOT_FULL;
93
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
= SLOT_FULL;
cout << endl << "Slots marked with an 'I' are available "
<< "for individual lessons:" << endl << endl;
print_schedule(slots, 'I', '_');
94
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
}
else if ((com == 'g') || (com == 'G')) // Group lessons
{
// Make a new schedule that has full slots where _either_ Jeff
// and Anna are busy.
int slots[NUM_DAYS][NUM_SLOTS];
cout << endl << "Slots marked with a 'G' are available "
<< "for individual lessons:" << endl << endl;
print_schedule(slots, 'G', '_');
}
}
while ((com != 'q') && (com != 'Q'));
return 0;
}
95
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
instructor = -1;
day = -1;
slot = -1;
96
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
slot--;
}
97
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
18.
// ****************************************************************
//
// Ch7Proj18.cpp
//
// Modification of the previous program to store/load schedules to disk.
//
// ****************************************************************
#include <fstream>
#include <iostream>
// Make constants for the number of slots each day and the number
// of days. (Such constants may be particularly useful in cases
// where we have functions that take 2-dimensional arrays as arguments,
// as a constant used in the function header will convey information
// about the order of the dimensions.)
const int NUM_SLOTS = 4;
const int NUM_DAYS = 4;
// Constants for the values that we will store in the int[][] arrays
// representing each instructor's schedule
const int SLOT_OPEN = 0;
const int SLOT_FULL = 1;
// Saves the schedules to a file, prompting the user for a file name
void save(int jeff[][NUM_SLOTS], int anna[][NUM_SLOTS]);
// Loads the schedules from a file, prompting the user for a file name.
// Any data that was previously in the arrays will be overwritten.
void load(int jeff[][NUM_SLOTS], int anna[][NUM_SLOTS]);
98
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
int main()
{
using namespace std;
jeff[0][0] = jeff[0][3]
= jeff[1][0] = jeff[1][1] = jeff[1][2] = jeff[1][3]
= jeff[2][1] = jeff[2][2] = jeff[2][3]
= jeff[3][1]
= SLOT_FULL;
99
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
cout << endl << "Slots marked with an 'I' are available "
<< "for individual lessons:" << endl << endl;
print_schedule(slots, 'I', '_');
}
else if ((com == 'g') || (com == 'G')) // Group lessons
{
// Make a new schedule that has full slots where _either_ Jeff
// and Anna are busy.
int slots[NUM_DAYS][NUM_SLOTS];
cout << endl << "Slots marked with a 'G' are available "
<< "for individual lessons:" << endl << endl;
print_schedule(slots, 'G', '_');
}
100
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
return 0;
}
101
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
instructor = -1;
day = -1;
slot = -1;
102
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
jeff[day][slot] = new_slot_value;
}
}
else
{
if (anna[day][slot] == new_slot_value)
{
cout << endl << "That slot is already ";
if (new_slot_value == SLOT_OPEN)
{
cout << "free";
}
else
{
cout << "scheduled";
}
cout << "." << endl;
}
else
{
anna[day][slot] = new_slot_value;
}
}
}
// Saves the schedules to a file, prompting the user for a file name
void save(int jeff[][NUM_SLOTS], int anna[][NUM_SLOTS])
{
using namespace std;
char file_name[16];
ofstream out_stream;
cout << endl << "Enter the name of a file to save the schedules to: ";
cin >> file_name;
out_stream.open(file_name);
// If we can't open the file, we'll just write an error message and
// continue. This gives the user a chance to try again, with a
// different file name. Exiting would cause the user to lose any
// changes they had made.
if (out_stream.fail())
{
103
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
cout << "ERROR: Could not open file '" << file_name << "'." << endl;
}
else
{
save_schedule(out_stream, jeff);
save_schedule(out_stream, anna);
out_stream.close();
}
}
// Loads the schedules from a file, prompting the user for a file name.
// Any data that was previously in the arrays will be overwritten.
void load(int jeff[][NUM_SLOTS], int anna[][NUM_SLOTS])
{
using namespace std;
char file_name[16];
ifstream in_stream;
cout << endl << "Enter the name of a file to load the schedules from: ";
cin >> file_name;
in_stream.open(file_name);
// If we can't open the file, we'll just write an error message and
// continue. This gives the user a chance to try again, with a
// different file name. Exiting would cause the user to lose any
// changes they had made.
if (in_stream.fail())
{
cout << "ERROR: Could not open file '" << file_name << "'." << endl;
}
else
{
load_schedule(in_stream, jeff);
load_schedule(in_stream, anna);
in_stream.close();
}
}
104
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
// ****************************************************************
//
// Implementation of a shoulder-surfing resistant password that
// incorporates random challenges. The actual password is 31337.
// The digits of the entered password are extracted using / and %.
//
// ****************************************************************
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main( )
{
int actual[] = {3, 1, 3, 3, 7};
int passwordMap[10];
int enteredPassword[5];
105
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
{
if (enteredPassword[i] != passwordMap[actual[i]])
mismatch = true;
}
if (mismatch)
cout << "Invalid password." << endl;
else
cout << "Your password matches! " <<
"You have been authenticated." << endl;
106
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
It should be noted at this point that I have assumed g++ with Linux, specifically g++ 3.0.x
under Debian Linux as the programming environment. I have tested much of this under the
MS VC++ 6 and Borland 5.5 command compilers. Borland C++, VC++ 6.0 (and most
other compilers) give very much the same behavior as g++ and Linux for the programs
presented here.
Students that come to C++ from one of the more protective languages such as Pascal or
Java will find the low level, non-protective C/C++ array notion to be a concern at the least.
I list here are some of these concerns, and present a bit of the reasoning behind them. I
usually discuss these ideas in my class room presentation of the array concept.
C++ has adopted the notion of array from the C language without change. In C++ the
notion of array is quite 'low level'. By this, I mean that in C++, arrays, along with pointers
and the notion of conversion of an array name to a pointer, provide a mechanism that
closely models memory and address concepts in traditional computer hardware. The
concept is both simple and general, and has the potential to be quite efficient -- and, in
careless hands, quite dangerous.
Unlike Java and Pascal, the C++ array mechanism provides no protection against abuse and
error. Ellis and Stroustrup (ARM page 137) point out the low-level nature of C++ arrays
result in the following major limitations:
107
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
This last property means that passing an array as a function parameter is inherently
dangerous.
If any of the properties mentioned are a problem in programming, the programmer always
has the option to create an ADT by embedding the array in a class that overloads the
indexing [] operator to provide array bounds checking, variable array size, or otherwise
addresses the above properties that are seen as shortcomings in a given setting.
Be careful with the terminology. The text points out that there is much terminology
associated with the array concept, and it varies greatly from author to author. The problems
will usually be with students who have some programming experience, but not enough to
allow them to be comfortable with a change in the words used to describe these ideas.
Students who have studied languages that provide both start and ending array indices,
where both ends are usable have a particular problem with the asymmetric array bounds.
With Pascal, for example, unless a problem calls for the array indices to start at some value
other than 1, Pascal arrays traditionally start at 1 and run to the given size. On the other
hand, C/C++ arrays run from 0 to one less than the array size. The starting index is not
mentioned in the declaration, and the number that is mentioned, the size of the array, is not
a usable index value.
My students tend to confuse the use of x[4] in a declaration, as in int x[4]; with
the use of x[3] in an access to the array. I think the problem should be mentioned to your
classes. This chapter of the text discusses this idea.
108
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
As mentioned in the opening paragraph, C/C++ arrays do not provide array bounds
checking, so if array bounds are exceeded, strange results may occur.
You will hear students say "With a bad write to memory, you can cause the hard disk to be
reformatted." This isn't going to happen, especially in systems with memory protection..
My students appreciated being told this comforting bit of information. Most PCs today
have IDE controllers. These controllers do not have the capability to low-level format a
hard disk without a utility from the manufacturer. The few SCSI controllers that exist in
PCs may have disk utilities in ROM. An inadvertent write to certain addresses could
possibly start a disk utilities menu on a machine with an operating system that does not
protect memory. This is in fact unlikely, and if it did happen, it is unlikely to cause
unintended mischief.
Finally, an understanding of what happens when you index into an array based on the
memory model presented in the text is of great importance.
An indexed array variable is just a variable having the array's base type. Hence there is
nothing special about sending it to any function that accepts such argument, except that it
looks unfamiliar.
For my students, I emphasize that the whole array is not being sent to the function, just the
element of the array indicated by the index.
If you wanted to have an array whose size you could set at runtime, you might write the
following code. Unfortunately, this is illegal, though some compilers (including g++) allow
it.
109
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
//File: array_bounds.cpp
//To test behavior when array bounds are set, used, and
//violated
#include <iostream>
int main()
{
using namespace std;
int x[10] = {0, 1,2,3,4,5,6,7,8,9};//Ok, size is an
//int constant
int n;
cin >> n;
int y[n]; //Line 12 - Here we have (illegally) declared
//an array of non-constant size
for( int i = 0; i < n; i++)
cout << (y[i] = x[i]) << " " ;
cout<< endl;
return 0;
}
The C++ Standard says that the index expression must be a constant expression. The
Standard says further that a constant expression can involve only literals (such as 937,
true, or 1.23), enumerators (enum identifiers) and const values of integral types
initialized with constant expressions, sizeof expressions. We violate the rule that we must
have const integral values initialized by const expressions.
110
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
The bottom line is that array size must be known at compile time. The alternative is to
dynamically allocate space on the heap. That is treated later in the text.
When passing arrays, the array name is converted to a pointer to the first array element,
hence all that the function receives is the address of the first array element. All the function
can know is the type as specified in the function declaration and the starting address of the
array but not the array size. This is sometimes referred to as “array type deterioration”.
The consequence is that passing an array parameter is not pass-by-value, since changing the
array element in the function changes the argument array element. In spite of the fact that
changing the parameter changes the caller’s argument, this is not precisely pass-by-
reference either, because the called function doesn't know the size of the array. We call this
parameter passing mechanism "passing an array parameter."
Precisely, array parameters pass the address of the first element of the array, by value.
Having the address enables the called function to change the argument by indexing the
formal parameter and making an assignment.
There are only two places in C++ where the empty array index operator may be used: one,
where an array is declared with initializers, and in an array parameter for a function:1
A reminder: A use of the const keyword is both a promise by the programmer to the
compiler and a request that the compiler hold the programmer to the promise. The promise
1
There is one other place: the delete operator applied to an array allocated on the free-store
uses empty [] indexing punctuators, but the student knows nothing of this until the pointers
chapter.
111
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
is that the programmer will not write code that can change variables affected by the
const.
The case of a class member function that is declared with the const keyword is still a
promise, but is slightly different:
Here the promise is that the programmer will not to write code in this member function that
could change the calling object.
The following member declaration promises not to write code in the definition of this
function that will change the value of the parameter x in the function, which would
consequently change the caller’s argument.
It is possible to return a reference from a function. This allows the function to be used as an
l-value, i.e., the function call can be assigned. If the function is declared to return a const
reference, this use of const promises not to use the function call as an l-value. We will
treat this when we deal with operator overloading, and only mention it here for
completeness.
Plainly put, a function cannot return an array, not really, any more than a function can
receive an array as a parameter. The parallel is exact. If we build an array inside a function
then return the array as a function value, the only thing that is returned is a pointer to a base
type object that points to the first array element. We will deal with pointers in Chapter 9.
It is worthwhile to mention to the instructor at this point that there is great danger in
returning an array from a function. There is the temptation to declare a local array in a
function, then to return a pointer to the array as the value of a function. When the function
112
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
returns, all local variables, in particular, local arrays go away. The consequence is that
memory is being referred to that is no longer allocated, indeed, may be allocated to some
other use. The problem is that if it works, then it can work for some time, only changing
when some other change is made in the code. Then subtle changes in the operation of the
program can drive someone crazy.
The programming examples and the Case Study from the text provide more than just
illustrations of the uses of arrays as data types and as function parameters. These case
studies give examples of program design, testing, and several important algorithms of
important categories.
This case illustrates top-down design, array use and array parameters, and testing. The
production array introduces the notion that it isn't necessary to use the actual numbers in a
problem as indices into arrays. Rather, this problem uses shifted plant numbers for indices.
The testing of the components of this program is an interesting study. Both top-down and
bottom-up testing are illustrated here. The all important boundary cases are tested, as well
as in-the-middle values. Boundary testing helps find off-by-one errors.
This is an important section. The examples here introduce the notions of partially filled
arrays, searching and sorting. Frequently, we will know something about the largest
number of data we will need to manage, but much of the time the number of data will be
less than the maximum. We do not want to have to write a version of our analysis program
for every size of data. The tool we need is the partially filled array.
113
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 9e Chapter 7
Searching and sorting are very important topics in Computer Science. Donald Knuth said
that much of computer science was encompassed by searching and sorting.
The algorithms presented are insertion sort and linear search. In my opinion, the simplest
reasonable algorithms ought to be the introductory examples, and this is the text’s method.
In fact, the programmer should always design for correctness and clarity first, and worry
about efficiency after it is determined by testing that the simplest solution is deficient in
speed or some other way.
"The fastest algorithm can frequently be replaced with one that is almost as fast and
much easier to understand,"
114
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Another random document with
no related content on Scribd:
IT almost seemed as if the guitar helped Ronald on to
perfect recovery. As the spring days advanced, his strength
increased, and Doctor Warstone's visits were discontinued.
How much I missed those visits I never owned. I think the
influence of that good man's strong nature and wise,
cheerful words had sustained me unawares. And when I lost
sight of the kind face, and ceased to hear the friendly voice,
I became conscious of my own weakness.
"Ida Lorimer."
By-and-by the clock struck seven, and, for the first time
since my marriage, I sat down to dinner alone. It was then
that I began to realise what it was to feed on the "bread of
affliction." Ronald's empty place deprived me of all appetite,
and the chicken, which nurse had roasted to perfection,
went back to the kitchen almost untasted. In my remorse
and loneliness, I was even more severe on myself than
there was any need to be. The vixenish wife had driven her
much-enduring husband out of doors to seek his food
elsewhere! It was quite likely that, sickened with grief and
heartache, he would go without a dinner altogether.
But those we love best are precisely the people who can
never be made to see with our eyes. I knew that Ronald
would not be induced to distrust Greystock at my bidding;
and as I was still smarting from the consciousness of having
spoken unadvisedly once that day, I would not commit a
second blunder. So I owned meekly that I was over-tired
and over-worn, and let Ronald soothe me and wait on me to
his heart's content.
"I don't know," he said, "I can't help asking myself the
same question every time I play it. If I could only
remember how I learnt it first, I could solve the mystery."
CHAPTER VIII.
MARIAN.
The door closed behind him, and again I was left alone
with my misery. I was young, and there is a tendency in
youth to believe that every grief will be eternal.
"My dear child," she said, sitting down on the sofa and
drawing me to her side, "we must have a long talk. As to
freedom from care, do you really think that any married
woman can reasonably expect that? I am single, you see,
and so I suppose you will be surprised at my remark. But—"
But Marian was not one of those people who are always
in such a hurry to gain one's confidence that they will not
give one time to open one's heart. When she had got me
beside her on the sofa, she began to talk about herself and
her own concerns, explaining the circumstances that had
brought her to London, and telling me some good news in
her own simple, natural way.
"Yes, I have never parted with it. Why, Louie, you have
a guitar here! Is it yours?"
"There are words set to that air," she said, "but I cannot
recall them now. Who was it that ever played and sung this
melody to me? I wish I knew."
"I will play the air once more," she said, taking up the
guitar again. "It is very simple, but wonderfully sweet. Now
listen, and perhaps the words will come to me."