Make your own free website on Tripod.com

Tutorial 14

Arrays

 The instructor’s notes for this tutorial will consist of the following:

 

Overview

This tutorial covers the basic concepts involved with arrays. Implementing arrays in C++ is covered, as well as various algorithms using arrays. Some of these include displaying the contents of an array, searching an array, finding the highest entry in an array, and computing the average of an array’s elements. Note that two-dimensional arrays are covered, as well as the concept of parallel arrays.

 

Objectives

After completing the tutorial, the student will be able to:

 

Lecture Notes

Introduction to arrays

All of the variables you have used in the previous tutorials have been simple variables. A simple variable is one that is unrelated to any other variable in memory. In many programs, however, you may need to reserve a block of memory locations. This block of memory locations is referred to as an array.

An array is a group of variables that have the same name and data type, and are related in some way. The most commonly used arrays in programs are one-dimensional and two-dimensional arrays. A one-dimensional array is simply a column of variables. A two-dimensional array, on the other hand, resembles a table in that it has rows and columns.

Programmers use arrays to temporarily store related data in the internal memory of the computer. By doing so, a programmer can increase the efficiency of a program because data stored in an array (which is inside the computer in memory) can be both written and read much faster than data stored in a data file on a disk. Additionally, after the data is entered into an array, which typically is done at the beginning of the program, the program can use the data as many times as desired.

 

Declaring and initializing a one-dimensional array

As with variables, you must create, or declare, an array before you can use it. You can use any C++ built-in data type, as well as a class that you create, to declare the array. It is also good programming practice to initialize the elements of an array. Below is the syntax for declaring an array in C++:

datatype arrayname LEFTSQUAREnumberOfElementsRIGHTSQUARE = {initialValues};

where

(the elements are enclosed in braces {} and separated by commas)

When initializing the elements of an array, you may have an initial value for each element listed in the initialValues. When you do not specify an initial value for each element in a string array, Microsoft Visual C++ stores the empty string in the uninitialized elements. When you do not specify an initial value for each element in a numeric array, Microsoft Visual C++ stores the number zero (0) in the uninitialized elements. (Note that Microsoft Visual C++ will only initialize the uninitialized elements of an array if you provide at least one value in the initialValues, otherwise the elements may contain garbage). See Figure 14-3 on page 494 for examples of declaring and initializing one-dimensional arrays.

Subscripts and referencing an array element

Each of the array elements in memory is assigned a unique number, called a subscript (sometimes called the index). The first element in a one-dimensional array in C++ is assigned a subscript value of zero (0). Because the first element is assigned a subscript value of zero (0), the last subscript value for an array is one less than the number of elements in the array. For example, an array with ten (10) elements will be referenced using the subscripts zero (0) through nine (9).

You reference each element in an array by using the array’s name, followed by the element’s subscript enclosed in square brackets LEFTSQUARE RIGHTSQUARE. For example, to reference the first element of the array grades you would use the following: gradesLEFTSQUARE0RIGHTSQUARE. See Figure 14-5 on page 496 for examples of referencing array elements.

Note that the most effective method for referencing and processing each array element is with a loop. The for loop is the most popular since you may set the loop control variable to match the subscripts of the array.

Manipulating one-dimensional arrays

The elements in an array can be used just like any other set of variables. You can assign values to them, use them in calculations, display their contents, etc. Beginning on page 497 this tutorial covers a variety of code segments for manipulating arrays. Please begin reading through each of the code segments, with its corresponding set of pseudocode. This will show you how powerful arrays can be in a program. The different code segments along with its corresponding page number is listed below:

Passing arrays as parameters

As you have already learned in previous tutorials, data can be passed to functions either by value or by reference. Recall that in C++ variables are passed automatically by value. To pass a variable by reference in C++, you need to include the address-of (&) operator before the formal parameter’s name in the receiving function’s header. You also must include the address-of (&) operator in the receiving function’s prototype.

Unlike variables, arrays are passed automatically by reference rather than by value. When you pass an array, the address of only the first array element is passed to the receiving function. Because array elements are stored in contiguous locations in memory, the receiving function can use the address of the first element to locate the remaining elements. See Figure 14-13 on page 508 for an example of a program involving passing an array.

Parallel arrays

Remember that the elements within an array must be of the same type. However, if you wish to store two sets of data that had different data types, the concept of parallel arrays could be used. A parallel array is simply two or more arrays whose elements are related by their position (their subscript) within the arrays. See Figure 14-16 on page 511 for an example of a program utilizing the concept of parallel arrays.

Two-dimensional arrays

Many programs utilize two-dimensional arrays vs. using two one-dimensional arrays. As you learned earlier, a two-dimensional array resembles a table in that the elements are in rows and columns. As with one-dimensional arrays, you must declare and (optionally) initialize a two-dimensional array before you can use it.

The syntax for creating and initializing a two-dimensional array is similar to the syntax for creating and initializing a one-dimensional array (see Figure 14-17 on page 513 for a comparison). The two-dimensional array syntax, however, requires the programmer to provide two, rather than one, numberOfElements values after the array name. The first numberOfElements value represents the number of rows in the array, and the second numberOfElements value represents the number of columns. As with a one-dimensional array, you also can initialize a two-dimensional array at the same time you create the array.

Just as each element in a one-dimensional array is identified by subscript, each element in a two-dimensional array is identified by a unique combination of two subscripts. The first subscript represents the element’s row location in the array, and the second represents its column location. The computer assigns the subscripts to the elements when the array is created in memory. The first row subscript in a two-dimensional array is zero (0). The first column subscript in a two-dimensional array is also zero (0).

Note that while accessing and processing through a one-dimensional array is fairly straightforward with a looping structure, this same task with a two-dimensional array can be a little more tedious. If you want to access and process every element in a two-dimensional array, you will need to use two loops to do so. One of the loops keeps track of the row subscript, while the other keeps track of the column subscript.

Declaring and initializing a one-dimensional array of objects

Before you can store objects in an array, you need to create the class from which the objects will be made. Recall that creating a class involves determining the attributes and behaviors of the object you want to create. The attributes describe the object while the behaviors specify the tasks the object can perform. See Figure 14-22 on page 528 which defines a class to be used throughout the applications lesson example.

As you learned earlier in this tutorial in the concepts lesson, the syntax used to declare and initialize a one-dimensional array is datatype arraynameLEFTSQUAREnumberOfElementsRIGHTSQUARE = {initialValues};. When declaring an array of objects, datatype is the name of the object’s class. See Figure 14-25 on page 534, which shows two examples of declaring and initializing a one-dimensional array of objects.

Note that the first example in Figure 14-25 does not contain any initialValues. Because no initialValues are specified in the array declaration statement, the computer uses the default constructor to initialize the objects. The second example does contain initialValues. At times, you may want to assign specific values to the objects in the array when the array is created, rather than using the values provided by the default constructor function.

 

Solutions to Questions

  1. c All of the elements in an array have the same subscript.
  2. c subscript
  3. b replace the 500 amount with 510
  4. a replace the 20000 amount with 900
  5. a display 22000
  6. d if (x >= 0 && x <= 4)
  7. d while(x <= 4)
  8. {

    salesLEFTSQUARExRIGHTSQUARE = salesLEFTSQUARExRIGHTSQUARE + 100;

    x = x + 1;

    } //end while

  9. b while(x < 4)
  10. {

    total = total + numLEFTSQUARExRIGHTSQUARE;

    x = x + 1;

    } //end while

  11. a 0
  12. c 6
  13. b 5
  14. d 8
  15. c do not have to do anything because arrays are automatically passed by reference
  16. a reference
  17. a 0, 0
  18. a combination of two subscripts
  19. d "stock sub two four"
  20. d replace the 800 amount with 810
  21. a replace the 20000 amount with 900
  22. a display 1300
  23. d if(row >= 0 && row <= 1 && column >= 0 && column <= 4)

Solutions to Concept Lesson Exercises

1. int temperatureLEFTSQUARE10RIGHTSQUARE = {78, 89, 65, 90, 35, 20, 88, 101, 56, 99};

int x = 0;

while (x < 10)

{

cout << temperatureLEFTSQUARExRIGHTSQUARE << endl;

x = x + 1;

} //end while

 

2. string stateLEFTSQUARE50RIGHTSQUARE = {""};

void fillArray(string sLEFTSQUARERIGHTSQUARE)

{

ifstream inFile;

inFile.open("state.dat", ios::in);

int x = 0;

getline(inFile, sLEFTSQUARE0RIGHTSQUARE);

while (!inFile.eof() && x < 50)

{

x = x + 1;

getline(inFile, sLEFTSQUARExRIGHTSQUARE);

} //end while

I nFile.close()

} //end of fillArray function

 

3.

//T14ConE03.cpp - displays the number of days in a month

#include <iostream>

using namespace std;

int main()

{

//declare array

int monthDaysLEFTSQUARE12RIGHTSQUARE = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

//declare variable

int monthNum = 0;

cout << "Enter month number (99 to stop program): ";

cin >> monthNum;

while (monthNum >= 1 && monthNum <= 12)

{

cout << "This month has " << monthDaysLEFTSQUAREmonthNum - 1RIGHTSQUARE << " days." << endl;

cout << "Enter month number (99 to stop program): ";

cin >> monthNum;

} //end while

return 0;

} //end of main function

 4.

//T14ConE04.cpp - calculates and displays the total rainfall

#include <iostream>

#include <fstream>

using namespace std;

//function prototype

float calcTotal(float LEFTSQUARERIGHTSQUARE);

float calcAvg(float LEFTSQUARERIGHTSQUARE);

float calcHigh(float LEFTSQUARERIGHTSQUARE);

float calcLow(float LEFTSQUARERIGHTSQUARE);

int main()

{

//declare variable

int x = 0; //keeps track of subscripts

//declare array

float rainFallLEFTSQUARE12RIGHTSQUARE = {0.0};

//declare file object and open file

ifstream inFile;

inFile.open("t14cone04 - solution.dat", ios::in);

if (inFile.is_open())

{

//fill array with file data

while (x < 12 && !inFile.eof())

{

inFile >> rainFallLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

inFile.close(); //close file

//display total, average, high, and low rainfall

cout << "Total rainfall: " << calcTotal(rainFall) << endl;

cout << "Average rainfall: " << calcAvg(rainFall) << endl;

cout << "Highest rainfall: " << calcHigh(rainFall) << endl;

cout << "Lowest rainfall: " << calcLow(rainFall) << endl;

}

else

cout << "File could not be opened" << endl;

//end if

return 0;

} //end of main function

//*****program-defined functions*****

float calcTotal(float rLEFTSQUARERIGHTSQUARE)

{

int x = 0; //keeps track of subscripts

float total = 0.0; //accumulator

while (x < 12)

{

total = total + rLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

return total;

} //end of calcTotal function

float calcAvg(float rLEFTSQUARERIGHTSQUARE)

{

int x = 0; //keeps track of subscripts

float total = 0.0; //accumulator

while (x < 12)

{

total = total + rLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

return total / 12.0;

} //end of calcAvg function

float calcHigh(float rLEFTSQUARERIGHTSQUARE)

{

int x = 1; //keeps track of subscripts

float high = rLEFTSQUARE0RIGHTSQUARE; //keeps track of highest amount

while (x < 12)

{

if (rLEFTSQUARExRIGHTSQUARE > high)

high = rLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

return high;

} //end of calcHigh function

float calcLow(float rLEFTSQUARERIGHTSQUARE)

{

int x = 1; //keeps track of subscripts

float low = rLEFTSQUARE0RIGHTSQUARE; //keeps track of lowest amount

while (x < 12)

{

if (rLEFTSQUARExRIGHTSQUARE < low)

low = rLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

return low;

} //end of calcLow function

 

Contents of T14ConE04 – Solution.dat file

2.76

2.36

2.44

1.20

.40

.07

.04

.23

.54

.63

1.54

2.16

5.

//T14ConE05.cpp - writes updated prices to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

//function prototypes

void updatePrices(float LEFTSQUARERIGHTSQUARE);

void writeToFile(float LEFTSQUARERIGHTSQUARE);

int main()

{

//declare variable

int x = 0; //keeps track of subscripts

//declare array

float pricesLEFTSQUARE10RIGHTSQUARE = {0.0};

//declare file object and open file

ifstream inFile;

inFile.open("t14cone05 - solution.dat", ios::in);

if (inFile.is_open())

{

//fill array with file data

while (x < 10 && !inFile.eof())

{

inFile >> pricesLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

inFile.close(); //close file

//update prices

updatePrices(prices);

//write updated prices to file

writeToFile(prices);

}

else

cout << "File could not be opened" << endl;

//end if

return 0;

} //end of main function

//*****program-defined functions*****

void updatePrices(float pLEFTSQUARERIGHTSQUARE)

{

int x = 0; //keeps track of subscripts

float percent = 0.0;

cout << "Enter increase percentage as a whole number: ";

cin >> percent;

while (x < 10)

{

pLEFTSQUARExRIGHTSQUARE = pLEFTSQUARExRIGHTSQUARE * (1.0 + percent / 100.0);

x = x + 1;

} //end while

} //end of updatePrices function

 

void writeToFile(float pLEFTSQUARERIGHTSQUARE)

{

ofstream outFile;

outFile.open("t14cone05 - solution.new", ios::out);

if (outFile.is_open())

{

int x = 0; //keeps track of subscripts

outFile << fixed;

outFile.precision(2);

while (x < 10)

{

outFile << pLEFTSQUARExRIGHTSQUARE << endl;

x = x + 1;

} //end while

}

else

cout << "Error opening file" << endl;

//end if

} //end of writeToFile function

 

Contents of T14ConE05 – Solution.dat file

75.00

3.50

8.99

9.50

10.30

4.55

3.00

12.69

11.00

12.34

 

Contents of T14ConE05 – Solution.new file

90.00

4.20

10.79

11.40

12.36

5.46

3.60

15.23

13.20

14.81

 6.

//T14ConE06.cpp - writes updated prices to a sequential access file

#include <iostream>

#include <fstream>

using namespace std;

//function prototypes

void updatePrices(float LEFTSQUARERIGHTSQUARE);

void writeToFile(float LEFTSQUARERIGHTSQUARE);

int main()

{

//declare variable

int x = 0; //keeps track of subscripts

//declare array

float pricesLEFTSQUARE10RIGHTSQUARE = {0.0};

//declare file object and open file

ifstream inFile;

inFile.open("t14cone06 - solution.dat", ios::in);

if (inFile.is_open())

{

//fill array with file data

while (x < 10 && !inFile.eof())

{

inFile >> pricesLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

inFile.close(); //close file

//update prices

updatePrices(prices);

//write updated prices to file

writeToFile(prices);

}

else

cout << "File could not be opened" << endl;

//end if

return 0;

} //end of main function

 

 

 

 

 

 

 

//*****program-defined functions*****

void updatePrices(float pLEFTSQUARERIGHTSQUARE)

{

float percent = 0.0;

int num = 0;

cout << "Which item (1 - 10, 99 to stop)? ";

cin >> num;

while (num != 99)

{

if (num >= 1 && num <= 10)

{

cout << "Enter increase percentage as a whole number: ";

cin >> percent;

pLEFTSQUAREnum - 1RIGHTSQUARE = pLEFTSQUAREnum - 1RIGHTSQUARE * (1.0 + percent / 100.0);

}

else

cout << "Item number is invalid" << endl;

cout << "Which item (1 - 10, 99 to stop)? ";

cin >> num;

////end if

} //end while

} //end of updatePrices function

void writeToFile(float pLEFTSQUARERIGHTSQUARE)

{

ofstream outFile;

outFile.open("t14cone06 - solution.new", ios::out);

if (outFile.is_open())

{

int x = 0; //keeps track of subscripts

outFile << fixed;

outFile.precision(2);

while (x < 10)

{

outFile << pLEFTSQUARExRIGHTSQUARE << endl;

x = x + 1;

} //end while

}

else

cout << "Error opening file" << endl;

//end if

} //end of writeToFile function

Contents of T14ConE06 – Solution.dat file

75.00

3.50

8.99

9.50

10.30

4.55

3.00

12.69

11.00

12.34

 

Contents of T14ConE06 – Solution.new file

90.00

3.50

11.24

9.50

10.30

4.55

3.00

12.69

11.00

10.49

7.

//T14ConE07.cpp - displays the number of students earning a specific score

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int score = 0; //score to search for

int count = 0; //counter

//declare array

int scoresLEFTSQUARE20RIGHTSQUARE = {0};

//declare file object and open file

ifstream inFile;

inFile.open("t14cone07 - solution.dat", ios::in);

if (inFile.is_open())

{

//fill array with file data

while (x < 20 && !inFile.eof())

{

inFile >> scoresLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

inFile.close(); //close file

//get score

cout << "Enter score: ";

cin >> score;

//search for score

x = 0;

while (x < 20)

{

if (scoresLEFTSQUARExRIGHTSQUARE == score)

count = count + 1;

//end if

x = x + 1;

} //end while

//display count

cout << "Number of students: " << count << endl;

}

else

cout << "File could not be opened" << endl;

//end if

return 0;

} //end of main function

Contents of T14ConE07 – Solution.dat file

100

72

88

56

78

32

88

20

99

78

72

88

97

20

34

75

62

100

82

56

 

 

 

Two students earned 72, three earned 88, two earned 20, and 1 earned 99.

  

8.

//T14ConE08.cpp - displays the number of students earning

//a score in a specific range

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int minScore = 0; //minimum score in range

int maxScore = 0; //maximum score in range

int count = 0; //counter

//declare array

int scoresLEFTSQUARE20RIGHTSQUARE = {0};

//declare file object and open file

ifstream inFile;

inFile.open("t14cone08 - solution.dat", ios::in);

if (inFile.is_open())

{

//fill array with file data

while (x < 20 && !inFile.eof())

{

inFile >> scoresLEFTSQUARExRIGHTSQUARE;

x = x + 1;

} //end while

inFile.close(); //close file

//get scores

cout << "Enter minimum score: ";

cin >> minScore;

cout << "Enter maximum score: ";

cin >> maxScore;

//search for scores

x = 0;

while (x < 20)

{

if (scoresLEFTSQUARExRIGHTSQUARE >= minScore && scoresLEFTSQUARExRIGHTSQUARE <= maxScore)

count = count + 1;

//end if

x = x + 1;

} //end while

//display count

cout << "Number of students: " << count << endl;

}

else

cout << "File could not be opened" << endl;

//end if

return 0;

} //end of main function

 

 

Contents of T14ConE08 – Solution.dat file

100

72

88

56

78

32

88

20

99

78

72

88

97

20

34

75

62

100

82

56

 

 

 

Five students earned scores in the range 70 through 79, six earned scores in the range 65 through 85, and four earned scores in the range 0 through 50.

9.

//T14ConE09.cpp - displays a student's grade

#include <iostream>

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int points = 0;

//declare arrays

int minPointsLEFTSQUARE5RIGHTSQUARE = {0, 300, 350, 400, 450};

char gradeLEFTSQUARE5RIGHTSQUARE = {'F', 'D', 'C', 'B', 'A'};

//get total points

cout << "Enter total points (negative number to stop program): ";

cin >> points;

while (points >= 0)

{

//search for points in minPoints array

x = 0;

while (x < 5 && minPointsLEFTSQUARExRIGHTSQUARE <= points)

x = x + 1;

//end while

//display grade from grade array

cout << "Grade: " << gradeLEFTSQUAREx - 1RIGHTSQUARE << endl;

cout << "Enter total points (negative number to stop program): ";

cin >> points;

} //end while

return 0;

} //end of main function

 

 

10.

//T14ConE10.cpp - displays the square and square root of a number

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int num = 0;

//declare arrays

int numberLEFTSQUARE5RIGHTSQUARE = {2, 4, 6, 8, 10};

int squareLEFTSQUARE5RIGHTSQUARE = {pow(2,2), pow(4,2), pow(6,2), pow(8,2), pow(10,2)};

float squareRootLEFTSQUARE5RIGHTSQUARE = {sqrt(2), sqrt(4), sqrt(6), sqrt(8), sqrt(10)};

//get number

cout << "Enter the number (negative number to stop program): ";

cin >> num;

while (num >= 0)

{

//search for num in number array

x = 0;

while (x < 5 && numberLEFTSQUARExRIGHTSQUARE != num)

x = x + 1;

//end while

if (x < 5)

{

//display square and square root from square and squareRoot arrays

cout << "Square: " << squareLEFTSQUARExRIGHTSQUARE << endl;

cout << "Square root: " << squareRootLEFTSQUARExRIGHTSQUARE << endl;

}

else

cout << "Number is not in the array" << endl;

cout << "Enter the number (negative number to stop program): ";

cin >> num;

} //end while

return 0;

} //end of main function

 

 

 11.

//T14ConE11.cpp - generates lotto numbers

#include <iostream>

#include <ctime>

#include <cstdlib>

#include <fstream>

using namespace std;

int main()

{

//declare array

int numbersLEFTSQUARE50RIGHTSQUARELEFTSQUARE6RIGHTSQUARE = {0};

//declare variables

int row = 0;

int col = 0;

int randNum = 0;

int x = 0;

char found = ' ';

//declare file object and open file

ofstream outFile;

outFile.open("t14cone11 - solution.dat", ios::out);

 

 

if (outFile.is_open())

{

srand(time(NULL));

while (row < 50)

{

col = 0;

while (col < 6)

{

randNum = 1 + rand() % (54 - 1 + 1);

x = 0;

found = 'N';

while (x <= col && found == 'N')

{

if (numbersLEFTSQUARErowRIGHTSQUARELEFTSQUARExRIGHTSQUARE == randNum)

found = 'Y';

else

x = x + 1;

//end if

} //end while

if (found == 'N')

{

numbersLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE = randNum;

col = col + 1;

} //end if

} //end while

row = row + 1;

} //end while

row = 0;

col = 0;

while (row < 50)

{

col = 0;

while (col < 6)

{

outFile << numbersLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE << " ";

col = col + 1;

}

row = row + 1;

outFile << endl;

} //end while

//end while

outFile.close();

}

else

cout << "Error opening file." << endl;

return 0;

} //end of main function

 

 

Contents of T14ConE11 – Solution.dat file

49 28 18 53 20 8

54 29 18 31 33 4

40 53 1 19 44 36

40 1 17 50 32 27

43 39 6 42 15 27

16 34 13 15 28 6

49 46 19 26 10 5

19 36 1 30 20 26

43 17 35 48 29 54

44 42 10 41 25 39

44 6 13 39 50 15

52 39 40 20 31 11

39 29 8 12 7 43

25 39 6 30 4 53

32 3 2 51 52 39

12 10 51 4 30 47

4 32 39 17 38 21

13 19 22 6 18 23

10 43 8 6 11 15

7 31 39 6 9 52

50 21 4 54 30 10

36 21 20 43 40 4

8 48 20 21 2 32

13 19 38 48 47 22

2 40 35 43 13 47

6 3 43 11 31 13

5 48 2 4 32 34

4 30 1 40 50 2

31 21 50 42 41 43

45 22 26 30 6 43

13 54 6 28 27 52

34 23 21 2 22 4

34 24 27 42 41 4

45 1 38 39 34 53

3 22 35 19 27 41

38 39 5 30 36 25

42 32 25 3 28 50

15 31 12 52 11 46

22 16 10 44 46 53

45 12 7 26 33 30

43 9 23 42 36 51

11 38 48 23 47 51

39 34 30 16 14 41

43 40 5 20 2 23

22 7 45 14 34 53

27 40 48 14 1 10

24 44 31 21 43 26

6 15 31 52 13 4

8 22 9 25 42 31

33 39 47 15 20 35

12.

int row = 0;

int col = 0;

while (row < 3)

{

col = 0;

while (col < 4)

{

totQuantity = totQuantity + quantityLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE;

col = col + 1;

} //end while

row = row + 1;

}//end while

 

13. int populationLEFTSQUARE10RIGHTSQUARELEFTSQUARE4RIGHTSQUARE = {0};

 

14.

int quantityLEFTSQUARE5RIGHTSQUARELEFTSQUARE4RIGHTSQUARE = {0};

int row = 0;

int col = 0;

while (row < 5)

{

col = 0;

while (col < 4)

{

quantityLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE = 5;

col = col + 1;

} //end while

row = row + 1;

} //end while

15. itemLEFTSQUARE2RIGHTSQUARELEFTSQUARE4RIGHTSQUARE = 10000;

16.

//T14ConE16.cpp - calculates and displays

//domestic, international, and total sales

#include <iostream>

using namespace std;

int main()

{

//declare array

int salesLEFTSQUARE6RIGHTSQUARELEFTSQUARE2RIGHTSQUARE = {{12000, 10000}, {45000, 56000}, {32000, 42000}, {67000, 23000},{24000, 12000},

{55000, 34000}};

//declare variables

int row = 0; //keeps track of row subscript

int col = 0; //keeps track of column subscript

int company = 0; //company accumulator

int domestic = 0; //domestic accumulator

int internat = 0; //international accumulator

while (row < 6)

{

domestic = domestic + salesLEFTSQUARErowRIGHTSQUARELEFTSQUARE0RIGHTSQUARE;

internat = internat + salesLEFTSQUARErowRIGHTSQUARELEFTSQUARE1RIGHTSQUARE;

row = row + 1; //update row subscript

} //end while

//display total sales

cout << "Total domestic: $" << domestic << endl;

cout << "Total international: $" << internat << endl;

cout << "Total sales: $" << domestic + internat << endl;

return 0;

} //end of main function

17.

//T14ConE17.cpp - displays the number of times a value

//appears in an array

#include <iostream>

using namespace std;

int main()

{

//declare arrays

int numbersLEFTSQUARE5RIGHTSQUARELEFTSQUARE3RIGHTSQUARE = {{1, 3, 5}, {2, 4, 3},{1, 9, 8},{2, 6, 5},{7, 4, 3}};

int countsLEFTSQUARE9RIGHTSQUARE = {0};

//declare variables

int row = 0; //keeps track of row subscript

int col = 0; //keeps track of column subscript

int x = 1; //keeps track of number

int y = 0; //keeps track of subscript

while (x <= 9)

{

row = 0;

while (row < 5)

{

col = 0; //reset column subscript

while (col < 3)

{

//count

if (numbersLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE == x)

countsLEFTSQUAREx - 1RIGHTSQUARE = countsLEFTSQUAREx - 1RIGHTSQUARE + 1;

//end if

col = col + 1;

} //end while

row = row + 1; //update row subscript

} //end while

x = x + 1;

} //end while

//display counts

y = 0;

while (y < 9)

{

cout << "The number " << y + 1 << " appears " << countsLEFTSQUAREyRIGHTSQUARE << " time(s)." << endl;

y = y + 1;

} //end while

return 0;

} //end of main function

18.

//T14ConE18.cpp - calculates and displays

//highest score earned on midterm and final

#include <iostream>

using namespace std;

int main()

{

//declare array

int scoresLEFTSQUARE10RIGHTSQUARELEFTSQUARE2RIGHTSQUARE = {{98, 99}, {67, 54}, {78, 43}, {90, 86}, {88, 56},{78, 56}, {87, 88}, {72, 96},

{44, 67}, {66, 34}};

//declare variables

int row = 0; //keeps track of row subscript

int col = 0; //keeps track of column subscript

int midHigh = 0; //highest score on midterm

int finalHigh = 0; //highest score on final

midHigh = scoresLEFTSQUARE0RIGHTSQUARELEFTSQUARE0RIGHTSQUARE;

finalHigh = scoresLEFTSQUARE0RIGHTSQUARELEFTSQUARE1RIGHTSQUARE;

while (row < 10)

{

col = 0; //reset column subscript

while (col < 2)

{

if (scoresLEFTSQUARErowRIGHTSQUARELEFTSQUARE0RIGHTSQUARE > midHigh)

midHigh = scoresLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE;

//end if

if (scoresLEFTSQUARErowRIGHTSQUARELEFTSQUARE1RIGHTSQUARE > finalHigh)

finalHigh = scoresLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE;

//end if

col = col + 1; //update column subscript

} //end while

row = row + 1; //update row subscript

} //end while

//display high values

cout << "Highest score earned on midterm: " << midHigh << endl;

cout << "Highest score earned on final: " << finalHigh << endl;

return 0;

} //end of main function

19.

///T14ConE19.cpp - calculates and displays total sales

#include <iostream>

using namespace std;

//function prototype

int calcTotal(int LEFTSQUARERIGHTSQUARELEFTSQUARE2RIGHTSQUARE);

int main()

{

//declare array

int salesLEFTSQUARE6RIGHTSQUARELEFTSQUARE2RIGHTSQUARE = {{12000, 10000}, {45000, 56000},{32000, 42000},{67000, 23000},{24000, 12000},

{55000, 34000}};

//declare variable

int total = 0;

//accumulate sales

total = calcTotal(sales);

//display total sales

cout << "Total sales: $" << total << endl;

return 0;

} //end of main function

int calcTotal(int dollarsLEFTSQUARERIGHTSQUARELEFTSQUARE2RIGHTSQUARE)

{

int row = 0; //keeps track of row subscript

int col = 0; //keeps track of column subscript

int company = 0; //sales accumulator

while (row < 6)

{

col = 0; //reset column subscript

while (col < 2)

{

//accumulate sales

company = company + dollarsLEFTSQUARErowRIGHTSQUARELEFTSQUAREcolRIGHTSQUARE;

col = col + 1; //update column subscript

} //end while

row = row + 1; //update row subscript

} //end while

return company;

} //end of calcTotal function

20. Changes made to the original code are shaded.

//T14ConE20.cpp - updates the values stored in a one-dimensional array

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

//declare file object

ifstream inFile;

inFile.open("t14cone20.dat", ios::in);

if (inFile.is_open())

{

//declare array

int quantityLEFTSQUARE10RIGHTSQUARE = {0};

//declare variables

int x = 0; //keeps track of array subscripts

int amount = 0;

int increase = 0;

//fill array

inFile >> amount;

while (x < 10 && !inFile.eof())

{

quantityLEFTSQUARExRIGHTSQUARE = amount;

x = x + 1;

inFile >> amount;

} //end while

//get increase amount

cout << "Enter the increase amount: ";

cin >> increase;

//update array

x = 0;

while (x < 10)

{

//display current value

cout << "Current quantity: " << quantityLEFTSQUARExRIGHTSQUARE << " ";

//add increase to element

quantityLEFTSQUARExRIGHTSQUARE = quantityLEFTSQUARExRIGHTSQUARE + increase;

//display new value

cout << "New quantity: " << quantityLEFTSQUARExRIGHTSQUARE << endl;

x = x + 1; //update subscript

} //end while

inFile.close();

}

else

cout << "Error opening file." << endl;

return 0;

} //end of main function

Contents of T14ConE20 – Solution.dat file

10

15

20

45

63

24

19

67

12

10

Solutions to Application Lesson Exercises

 1.

//T14AppE01 - defines the GradeTable class

//*****declaration section*****

class GradeTable

{

public:

GradeTable();

GradeTable(int, char);

int getMinPoints();

char getGrade();

private:

int minPoints;

char grade;

};

//*****implementation section*****

GradeTable::GradeTable()

{

minPoints = 0;

grade = ' ';

} //end of default constructor

GradeTable::GradeTable(int m, char g)

{

minPoints = m;

grade = g;

} //end of constructor

int GradeTable::getMinPoints()

{

return minPoints;

} //end of getMinPoints function

char GradeTable::getGrade()

{

return grade;

} //end of getGrade function

 

//T14AppE01.cpp - displays a student's grade

#include <iostream>

#include "c:\cpp\myclasses\t14appe01 - solution"

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int points = 0;

//declare array of objects

GradeTable tableLEFTSQUARE5RIGHTSQUARE = {GradeTable(0, 'F'), GradeTable(300, 'D'), GradeTable(350, 'C'),

GradeTable(400, 'B'), GradeTable(450, 'A')};

//get total points

cout << "Enter total points (negative number to stop program): ";

cin >> points;

while (points >= 0)

{

//search for points in array

x = 0;

while (x < 5 && tableLEFTSQUARExRIGHTSQUARE.getMinPoints() <= points)

x = x + 1;

//end while

//display grade from array

cout << "Grade: " << tableLEFTSQUAREx - 1RIGHTSQUARE.getGrade() << endl;

cout << "Enter total points (negative number to stop program): ";

cin >> points;

} //end while

return 0;

} //end of main function

2.

//T14AppE02 - defines the Number class

//*****declaration section*****

class Number

{

public:

Number();

Number(int, int, float);

int getNum();

int getSquare();

float getSqRoot();

private:

int num;

int sqNum;

float sqRtNum;

};

//*****implementation section*****

Number::Number()

{

num = 0;

sqNum = 0;

sqRtNum = 0.0;

} //end of default constructor

Number::Number(int n1, int n2, float n3)

{

num = n1;

sqNum = n2;

sqRtNum = n3;

} //end of constructor

int Number::getNum()

{

return num;

} //end of getNum function

int Number::getSquare()

{

return sqNum;

} //end of getSquare function

float Number::getSqRoot()

{

return sqRtNum;

} //end of getSqRoot function

 

//T14AppE02.cpp - displays the square and square root of a number

#include <iostream>

#include <cmath>

#include "c:\cpp\myclasses\t14appe02 - solution"

using namespace std;

int main()

{

//declare variables

int x = 0; //keeps track of subscripts

int num = 0;

//declare array of objects

Number numArrayLEFTSQUARE5RIGHTSQUARE = {Number(2, pow(2,2), sqrt(2)), Number(4, pow(4,2), sqrt(4)),

Number(6, pow(6,2), sqrt(6)), Number(8, pow(8,2), sqrt(8)),

Number(10, pow(10,2), sqrt(10))};

//get number

cout << "Enter the number (negative number to stop program): ";

cin >> num;

while (num >= 0)

{

//search for num in array

x = 0;

while (x < 5 && numArrayLEFTSQUARExRIGHTSQUARE.getNum() != num)

x = x + 1;

//end while

if (x < 5)

{

//display square and square root from array

cout << "Square: " << numArrayLEFTSQUARExRIGHTSQUARE.getSquare() << endl;

cout << "Square root: " << numArrayLEFTSQUARExRIGHTSQUARE.getSqRoot() << endl;

}

else

cout << "Number is not in the array" << endl;

cout << "Enter the number (negative number to stop program): ";

cin >> num;

} //end while

return 0;

} //end of main function

 

 

3.

//T14AppE03 - defines the Sales class

//*****declaration section*****

class Sales

{

public:

Sales();

Sales(int, int);

int getDom();

int getInter();

private:

int dom;

int inter;

};

//*****implementation section*****

Sales::Sales()

{

dom = 0;

inter = 0;

} //end of default constructor

Sales::Sales(int n1, int n2)

{

dom = n1;

inter = n2;

} //end of constructor

int Sales::getDom()

{

return dom;

} //end of getDom function

int Sales::getInter()

{

return inter;

} //end of getInter function

//T14AppE03.cpp - calculates and displays total sales

#include <iostream>

#include "c:\cpp\myclasses\t14appe03 - solution"

using namespace std;

int main()

{

//declare array

Sales saleAmountsLEFTSQUARE6RIGHTSQUARE= {Sales(12000, 10000), Sales(45000, 56000), Sales(32000, 42000),

Sales(67000, 23000), Sales(24000, 12000), Sales(55000, 34000)};

//declare variables

int row = 0; //keeps track of row subscript

int col = 0; //keeps track of column subscript

int domestic = 0; //domestic accumulator

int internat = 0; //international accumulator

while (row < 6)

{

domestic = domestic + saleAmountsLEFTSQUARErowRIGHTSQUARE.getDom();

internat = internat + saleAmountsLEFTSQUARErowRIGHTSQUARE.getInter();

row = row + 1; //update row subscript

} //end while

//display total sales

cout << "Total domestic: $" << domestic << endl;

cout << "Total international: $" << internat << endl;

cout << "Total sales: $" << domestic + internat << endl;

return 0;

} //end of main function

4.

//T14AppE04 - defines the Product class

#include <string>

using namespace std;

//*****declaration section*****

class Product

{

public:

Product();

Product(string, int);

void assignData(string, int);

string getId();

int getPrice();

private:

string id;

int price;

};

//*****implementation section*****

Product::Product()

{

id = "";

price = 0;

} //end of default constructor

Product::Product(string pId, int pCost)

{

id = pId;

price = pCost;

} //end of constructor

void Product::assignData(string pId, int pCost)

{

id = pId;

price = pCost;

} //end of assignData function

string Product::getId()

{

return id;

} //end of getId function

int Product::getPrice()

{

return price;

} //end of getPrice function

 //T14AppE04.cpp - displays the IDs and prices

#include <iostream>

#include <fstream>

#include <string>

#include "c:\cpp\myclasses\t14appe04 - solution"

using namespace std;

int main()

{

//declare array of objects

Product itemsLEFTSQUARE5RIGHTSQUARE;

//declare file object and open file

ifstream inFile;

inFile.open("t14appe04 - solution.dat", ios::in);

if (inFile.is_open())

{

int x = 0; //keeps track of subscripts

string itemId = "";

int itemPrice = 0;

while (x < 5 && !inFile.eof())

{

getline(inFile, itemId, '#');

inFile >> itemPrice;

inFile.ignore(1);

itemsLEFTSQUARExRIGHTSQUARE.assignData(itemId, itemPrice);

x = x + 1; //update subscript

} //end while

inFile.close();

x = 0;

while (x < 5)

{

cout << itemsLEFTSQUARExRIGHTSQUARE.getId() << " " << itemsLEFTSQUARExRIGHTSQUARE.getPrice() << endl;

x = x + 1; //update subscript

} //end while

} //end if

else

cout << "Unable to open file." << endl;

return 0;

}

 

 

Contents of T14AppE04 – Solution.dat file

BX35#13

CR20#10

FE15#12

KW10#24

MM67#4

5.

//T14AppE05 - defines the Employee class

#include <string>

using namespace std;

//*****declaration section*****

class Employee

{

public:

Employee();

Employee(string, int);

string getName();

int getSalary();

private:

string name;

int salary;

};

//*****implementation section*****

Employee::Employee()

{

name = "";

salary = 0;

} //end of default constructor

Employee::Employee(string n, int s)

{

name = n;

salary = s;

} //end of constructor

string Employee::getName()

{

return name;

} //end of getName function

int Employee::getSalary()

{

return salary;

} //end of getSalary function

  Changes to the original code are shaded.

//T14AppE05.cpp - displays the values stored in the array

#include <iostream>

#include "c:\cpp\myclasses\t14appe05 - solution"

using namespace std;

int main()

{

//declare array

Employee empDataLEFTSQUARE5RIGHTSQUARE = {Employee("Carol Miller", 25000), Employee("Jesse Martinez", 35000),

Employee("Bill Black", 40000), Employee("Marla Johansen", 45000),

Employee("Harry Chen", 34000)};

//declare variable

int x = 0;

//display array contents

while (x < 5)

{

cout << empDataLEFTSQUARExRIGHTSQUARE.getName()

<< " " << empDataLEFTSQUARExRIGHTSQUARE.getSalary() << endl;

x = x + 1;

} //end while

return 0;

} //end of main function