Académique Documents
Professionnel Documents
Culture Documents
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.
1. Rainfall
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.
//File Ch10Prg1.cpp
//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 © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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>
#include <cstdlib>
struct monthly_rain
2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
int month;
double rain_fall;
double avg_rain_fall;
};
int main()
{
using namespace std;
int current_month;
3
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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. "
<< "Defaulting to graphical output." << endl;
output_bargraph( rainfall, current_month );
}
cout << "Y/y continues, any thing else quits";
cin >> ans;
}while( 'y' == ans || 'Y' == ans );
return 0;
}
4
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
void full_month_name(int);
cout << endl << "The actual rainfall: " << endl;
cout << "What is the current month? Please give the "
<< "number of the month (Jan = 0, etc." << endl;
5
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
6
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
7
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
8
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
9
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
break;
default: cout << "NO SUCH MONTH " << month << endl;
exit(1);
}
}
10
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//file: Ch10Prg1.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;
};
11
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
12
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
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
13
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 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.
14
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
15
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
. . . .
For month December Rainfall: 1.1
Now for the months in this year:
For month January Rainfall: 4.1
. . . .
For month April Rainfall: 3.7
Please choose between g)raphical and t)abular output
You chose the graphical output
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 *******************************************
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 ***************************************************
16
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
. . . .
. . . .
17
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
. . . .
For month April Rainfall: 3.7
Please choose between g)raphical and t)abular output
You typed neither of the choices. Defaulting to graphical output.
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 *******************************************
. . . .
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.
18
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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:
The changes necessary internal to the routines is illustrated here. We replace this following
loop from the input routine,
with this:
19
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
2. Hexadecimal Addition
Problem statement and my commentary are in comments in the following source.
20
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#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
// 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;
}
}
21
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
carry = nextCarry;
s = (x + y + carry)%16; // digit value
// cout << "s " << s << endl;
22
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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);
cout << endl << endl;
return 0;
}
/*
23
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
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
------------
24
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
*/
3. Delete Repeats
//File: ch7prb3.cpp
//
//Problem: to write (and test) a function that has a
//partially filled array of characters as a formal parameter.
//A partially filled array requires two parameters, the array
//itself and a size parameter. The function deletes all
//repeated letters from the array, and close up the 'empty'
//positions, then decrease the size parameter.
//Test this function.
#include <iostream>
25
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.";
26
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
array[k] = array[k+1];
j--; //backup, look at this character again!
size--;
}
}
}
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
reduced array size = 18
Now is the time for all good men to come to the aid of the country.
size = 67
reduced array = Now isthemfralgdncuy.
reduced array size = 21
4. Standard Deviation
// Ch7Prob4.cpp
//
// Define a function that takes a partially filled array of doubles
// as one of two arguments (the other is the size), and returns the
// standard deviation of the numbers in the partially filled array.
27
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double s[MAX_SIZE];
double stdDeviation, avg;
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";
28
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
return 0;
}
Count distinct entries in an array of user determined size. Maximum size is 50. No solution
is provided to this problem.
29
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
6. Insertion Sort
No solution is provided.
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.
//File: ch7prg7.cpp
//Purpose: to sum two large integers (up to 20 digits each).
//
//Input: digits of two integers
//It appears that a "partially filled array structure" is of
//use here.
//
//Output: the sum of the two large integers is written to the
//screen
//
//algorithm: computer version of the traditional paper and pencil
//algorithm.
30
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#include <iostream>
#include <cstdlib>
#include <cctype>
int main()
{
using namespace std;
31
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
32
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//Reverse array
for ( int k = 0; k < number.size/2; k++ )
{
int temp = number.digit[k];
number.digit[ k ] = number.digit[ number.size - 1 - k ];
number.digit[ number.size - 1 - k ] = temp;
}
}
33
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
34
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
if (sum.digit[i] > 9 )
{
carry = 1;
sum.digit[i] = sum.digit[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.digit[0] = 0;
}
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
35
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
you entered
2345676543456312987
Enter another integer, 20 digits or less
432256456785678689
you entered
432256456785678689
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
36
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
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.
37
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
//File: ch7prg7b.cpp
//The Adder problem without structures.
//Purpose: to sum two large integers (up to 20 digits each).
//
//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>
38
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#include <cctype>
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;
39
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
40
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//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;
}
}
41
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
42
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
8. Letter Frequency
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.
43
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
#include <iostream>
#include <cassert>
44
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#include <cctype>
struct char_freq
{
char ch;
int count;
};
45
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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;
}
46
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
47
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
list[i].count++;
success = true;
return success;
}
i++;
} while(i <= size);
assert(i <= 27); //Debugging aid, see the Text’sAppendix
//for the details of the Assert macro.
return success;
}
A data file
48
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
o 15
w 3
i 6
s 1
t 12
h 8
e 11
m 4
f 4
r 5
a 6
l 3
g 3
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
49
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
t 4
w 3
i 2
h 2
m 2
y 1
b 1
I 1
r 1
f 1
d 1
n 1
o 1
//File: ch7prg9.cpp
//
//9. Score a five-card poker hand into one of the following
// categories:
// nothing
// one pair
// two pairs
// three of a kind
// straight (in order, no gaps)
// flush ( all same suite, for example, all spades)
// full house (one pair and three of a kind)
// four of a kind
// straight flush (hand is both a straight and flush)
50
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//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.
//
//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.
51
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
#include <iostream>
#include <cstdlib>
#include <cctype>
//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,
52
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 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,
// EIGHT=6, NINE=7, TEN=8, JACK=9, QUEEN=10, KING=11,
// ACE=12;
//
//I tested these changes.
struct Card
{
Card_Suite suite;
Face_Value face;
};
53
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
// returns true
//else
// returns false
54
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//Postcondition:
//if the cards are in sequence,
// return true
//else
// return false
int main()
{
using namespace std;
55
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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 );
cout << endl << endl;
cout << "Y/y continues, other halts." << endl << endl;
cin >> ans;
}while ( 'Y' == ans || 'y' == ans );
}
56
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
break;
case ONE_PAIR:
cout << "One Pair";
break;
case TWO_PAIRS:
cout << "Two Pair";
break;
case THREE_OF_KIND:
cout << "Three of a Kind";
break;
case STRAIGHT:
cout << "Straight";
break;
case FLUSH:
cout << "Flush";
break;
case FULL_HOUSE:
cout << "Full House";
break;
case FOUR_OF_KIND:
cout << "Four of a Kind";
break;
case STRAIGHT_FLUSH:
cout << "Straight Flush";
break;
default:
cout << " Something is very wrong. Bad value ";
break;
}
}
57
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
Hand_Value value;
if ( is_straight(hand) )
if (is_flush( hand ))
return STRAIGHT_FLUSH;
if ( has_four(hand) )
return FOUR_OF_KIND;
if (is_full_house(hand) )
return FULL_HOUSE;
if (is_flush(hand) )
return FLUSH;
if (is_straight(hand) )
return STRAIGHT;
if ( has_three(hand) )
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;
}
58
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
break;
case '4': value = FOUR;
break;
case '5': value = FIVE;
break;
case '6': value = SIX;
break;
case '7': value = SEVEN;
break;
case '8': value = EIGHT;
break;
case '9': value = NINE;
break;
case 't': value = TEN;
break;
case 'j': value = JACK;
break;
case 'q': value = QUEEN;
break;
case 'k': value = KING;
break;
case 'a': value = ACE;
break;
default: cout << "Bad face value. Aborting!";
exit(1);
}
}
59
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
case TWO: cout << 2;
break;
case THREE: cout << 3;
break;
case FOUR: cout << 4;
break;
case FIVE: cout << 5;
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);
}
}
60
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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);
61
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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;
}
62
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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
&&hand[2].face == hand[3].face
||
hand[2].face == hand[3].face
63
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
&&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 )
return 1;
else
return 0;
}
64
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
65
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
//File: sort_hand.cpp
//
//Most of the changes were made with a query-search command.
//
#include <iostream.h>
66
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
struct Card
{
Card_Suite suite;
Face_Value face;
};
67
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
int index_of_next_smallest;
for (int index = 0; index < number_used - 1; index++)
{//Place the correct value in a[index]:
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.
}
}
68
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
index_of_min = index;
//Assert: min is the smallest of a[start_index].face
//through a[index].face
}
return index_of_min;
}
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.
69
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
A command that runs the program after compilation, with the above data.
Note that the output is a little nicer than the interactive run:
70
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
Clubs 2
Diamonds 2
Clubs 4
Clubs 5
Spades Ace
value of hand is: One Pair
71
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
. . .
72
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
10. tic-tac-toe
This program is to ask for moves alternately from players X and O. The display should be
board-like:
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
73
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
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 MS DOS you should use system("cls"), since the MS DOS command to clear
the screen is "cls".
I was pleased and surprised with the ease of initialization of the array data member in the
constructor:
Game::Game():array("123456789")
{
}
I was disappointed to find this does NOT WORK with BC++! (It is one of the g++
extensions to the language. I warn my students about these and in the interest of
portability, and I do not allow their use.) I replaced this nonstandard initialization with a
standard array initialization using a loop in this constructor in the program.
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
74
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
// ********************************************************************
// Ch7Proj10.cpp
//
// 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[]);
// ====================
// 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;
75
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
board[i] = '1' + i;
}
76
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
// .
// .
// last A B D C
//
// Program requests number of rows.the displays the seating pattern
// with an X for occupied rows
//
// 1 X B C D
// 2 A X C D
// 3 A B C D
// 4 A B X D
// .
// .
// .
// k A B C D
// .
// .
// .
// n-1 A B C D
// n A B C D
//
// The program then requests a choice of seat.
// If the seat if availabler, then the seating display is updated.
// otherwise, the program requests another choice of seat.
//
// KNOWN BUGS:
// If the user incorrectly enters the seat letter for the row
// designation, the program goes into a continuing loop. Control C
// under most operating systems stops the program. It would be a
// nice enhancement to make the input more robust.
#include <iostream>
#include <cstdlib>
#include <cstddef>
Seating seatAssignment;
int main()
{
using std::cout;
using std::cin;
77
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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 << " ";
}
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"
78
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
return 0;
}
/*
Typical run
Savitch Airlines
Seat Reservation Program.
Reserved seats are marked 'X'. Others are available.
A B C D
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.
79
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
*/
14.
//
***********************************************************************
// Ch7Proj14.cpp
//
// This program searches a list of the top 1000 most popular
// Baby Names from the year 2004 and outputs the popularity rank.
// It uses arrays to store the list of names.
//
//
***********************************************************************
#include <iostream>
#include <fstream>
#include <cstdlib>
// ======================
// main function
// ======================
int main()
{
string targetName; // Target name
string boyName, girlName; // Temp boy/girl name
80
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
// 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();
// Output results
cout << targetName << " is ";
81
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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;
}
15.
//
***********************************************************************
// Ch7Proj15.cpp
//
// 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>
// Function prototypes
int findMax(const int a[]);
void saveSVG(int a[]);
82
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
// ======================
// 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;
out_stream.open("Ch7Proj15.svg");
if (out_stream.fail())
{
cout << "Output file opening failed." << endl;
exit(-1);
83
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
}
// 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;
84
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
}
saveSVG(bars);
return 0;
}
16.
// ****************************************************************
//
// Ch7Proj16.cpp
//
// 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;
int temp;
85
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
cards[2][0]=5; cards[2][1]=5;
cards[2][2]=6; cards[2][3]=6;
cards[3][0]=7; cards[3][1]=7;
cards[3][2]=8; cards[3][3]=8;
// ======================
// 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;
// ======================
// main function
// ======================
86
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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;
87
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
88
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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:
89
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e 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.
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. If a Windows, DOS,
90
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
or Mac platform is used, the potential for hanging the machine by overwriting a return
address for a function exists.
If you are using an operating system that runs with protected memory, such as Sun, a Unix
flavor, Linux, BSD, Windows NT, 2000, and XP or one of the (few) other fully protected
mode operating systems, an array index very far out-of-bounds can cause a run time error
(reported by Linux and a few other systems as a segmentation violation). Sun, HP, VAX,
and many other workstations run fully protected mode operating systems. Note that
Microsoft Windows 9x and Me do not protect against much of anything. Upgrade now if
you are afflicted with 9x or Me. Windows 2000 and XP are significantly better, but not
perfect in this regard.
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.
91
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
//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;
}
92
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
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.
93
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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 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.
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.
94
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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
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
95
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
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.
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,"
96
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
Arrays can have any C++ type for its base type. A class or struct can have any C++ type
for members. There are unlimited combinations of arrays of classes and classes with array
members.
Arrays of Classes
Here the student must do the Self-Test exercises, and the code fragments should be tested
by embedding them in small programs as suggested in the exercises. This stuff isn't
difficult, but it does require substantial exposure over a period of time to internalize the
ideas.
I suggest the instructor strongly encourage students to create many examples for
themselves, making inquiry of the compiler about language details. While the language
Standard is the ultimate authority about what the C++ language should be, and the text
lucidly explains the details, it is the compiler that you are using that is the authority on
what C++ language your compiler accepts. This is important whether the questions
concern syntax or the meaning of a code segment.
Here is an example of the many small programs asking the compiler about details of the
language that should be written in the learning of this language. I am inquiring about use
of constructor lists for initializing arrays of class objects. You may wish to mention that
many programmers use this style of initialization in constructors.
Money difference[5];
97
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
You can use a list of constructor calls to initialize an array of objects. In fact, if a
parameterized constructor of the appropriate type is present, you may use lists of objects of
any type that the constructors can use to initialize an array of class objects. The constructor
will be automatically called. As we shall see in the example, grouping the values is
sometimes necessary.
//File Z.cpp
//to test initializing arrays of class objects with a
//non-constructor list
#include <iostream.h>
class Z
{
public:
Z();
Z(int x);
Z(int x, int y );
int get_i();
int get_j();
//other public members
private:
int i;
int j;
};
Z::Z():i(0),j(0)
{
cout << "default constructor called" << endl;
}
Z::Z(int x):i(x),j(0)
98
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
{
cout << "one parameter constructor called" << endl;
}
int get_i()
{
return i;
}
int get_j()
{
return j;
}
int main()
{
int k;
//Here we call the one parameter constructor, the default
constructor,
//and the two parameter constructor.
99
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
}
cout << endl;
Here is an alternative. Notice that you MUST have a default constructor for this to compile. Here,
two constructors are called for each element in the array: default constructor is called
implicitly(meaning the compiler generates the call) and the one parameter constructor is called
explicitly.
Z y[3];
This causes the automatic calling of the Z(int) constructor for each initializer in the list.
Z x[] = { 0, 1, 2, };
Here the two parameter constructor is called. The grouping of the initializers is necessary
in order to have the two parameter constructor called.
Z zz[] = { {0,1},{2,3},{4,5}};
100
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
To get two parameter constructors called, you must group the initializers:
Here we mix things a bit. Two calls to the int parameter constructor, and two calls to the
two parameter constructor.
Z xx[4] = { 0,1,{2,3},{4,5}};
The text points out that arrays are eligible to be members of a class. Initialization of
array data members must be done within a constructor, in much the same way arrays
outside the class are initialized from variable data.
Here is one additional example that uses a slightly different partially filled array with fixed
maximum size:
//File: array-as-class-members.cpp
//to investigate the initialization of array members of a
//class
#include <iostream>
101
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
class Has_array
{
public:
Has_array()
{
size = 0;
}
Has_array( int arr[], int s )
{
for ( int i = 0; i < s; i++)
x[i] = arr[i];
size = s;
}
friend ostream& operator << ( ostream& outs,
const Has_array & obj )
{
for ( int i = 0; i < obj.size; i++)
{
cout << obj.x[i] << " ";
}
return outs;
}
friend istream& operator >> ( istream& ins, Has_array & obj )
{
int i = 0;
while ( i < MAX_SIZE && ins >> obj.x[i] )
i++;
obj.size = i; //i should be the number of objects
transferred
102
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 6e Chapter 7
int sizeOfIt()
{
return size;
}
private:
int x[MAX_SIZE];
int size;
};
int main()
{
int a[] = {1,2,3,4};
int size = 4;
Has_array u;
Has_array v( a, siz);
cout << "Enter up to 5 integers, <CR> after each. "
<< "<EOF> to terminate input. " << endl;
cin >> u;
cout << "you entered " << u.sizeOfIt()
<< " integers, which are: "
<< u << endl;
cout << "here is the array built into the program: "
<< endl << "its size is " << v.sizeOfIt() << endl;
cout << v << endl;
}
103
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley