Arrays - Introduction to Computer Programming | CPE 112, Assignments of Engineering

Material Type: Assignment; Class: INTRO COMPUTER PROG FOR ENGR; Subject: Computer Engineering; University: University of Alabama - Huntsville; Term: Unknown 1989;

Typology: Assignments

Pre 2010

Uploaded on 07/23/2009

koofers-user-ac6
koofers-user-ac6 🇺🇸

9 documents

1 / 16

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 12 Arrays
Chapter 12
EXERCISE ANSWERS
Exam Preparation Exercises
2. False
3. a. float floatArray[24];
b. int intArray[500];
c. double doubleArray[50];
d. char charArray[10];
4. const int CLASS_SIZE = 30;
float quizAvg[CLASS_SIZE];
6. a. for (cIndex = BLUE; cIndex <= BLACK; cIndex = Colors(cIndex + 1))
count[cIndex] = 0;
b. for (rIndex = 0; rIndex < SIZE; rIndex++)
rainbow[rIndex] = WHITE;
c. int counter = 0;
for (rIndex = 0; rIndex < SIZE; rIndex++)
if (rainbow[rIndex] == GREEN)
counter++;
d. cout << count[BLUE] << endl;
e. int sum = 0;
for (cIndex = BLUE; cIndex <= BLACK; cIndex = Colors(cIndex + 1))
sum = sum + count[cIndex];
8. The For statement incorrectly causes index to range from 1 through 4 instead of 0 through 3. Output of the
(nonexistent) array element arr[4] accesses the memory location just beyond the end of the array. This memory
location evidently contained the value 24835.
10. sample [0] [1] [2] [3] [4] [5] [6] [7]
1 1 1 1 −1 −1 −1 −1
11. sample [0] [1] [2] [3] [4] [5] [6] [7]
0 101 2 103 4 105 6 107
12. All the components of an array must be of the same data type; the components of a record may be of different types.
The components of an array are accessed by an index; the components of a record are accessed by a member name.
13. True
15. a. 10 b. 3 c. 3 d. 10 e. 30 f. 30 g. row h. row
16. a. c.
b.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Arrays - Introduction to Computer Programming | CPE 112 and more Assignments Engineering in PDF only on Docsity!

Chapter 12

EXERCISE ANSWERS

Exam Preparation Exercises

  1. False
  2. a. float floatArray[24];

b. int intArray[500]; c. double doubleArray[50]; d. char charArray[10];

  1. const int CLASS_SIZE = 30;

float quizAvg[CLASS_SIZE];

  1. a. for (cIndex = BLUE; cIndex <= BLACK; cIndex = Colors(cIndex + 1))

count[cIndex] = 0; b. for (rIndex = 0; rIndex < SIZE; rIndex++) rainbow[rIndex] = WHITE; c. int counter = 0; for (rIndex = 0; rIndex < SIZE; rIndex++) if (rainbow[rIndex] == GREEN) counter++; d. cout << count[BLUE] << endl; e. int sum = 0; for (cIndex = BLUE; cIndex <= BLACK; cIndex = Colors(cIndex + 1)) sum = sum + count[cIndex];

  1. The For statement incorrectly causes index to range from 1 through 4 instead of 0 through 3. Output of the

(nonexistent) array element arr[4] accesses the memory location just beyond the end of the array. This memory location evidently contained the value 24835.

  1. sample [0] [1] [2] [3] [4] [5] [6] [7]

1 1 1 1 −1 −1 −1 −

  1. sample [0] [1] [2] [3] [4] [5] [6] [7]

0 101 2 103 4 105 6 107

  1. All the components of an array must be of the same data type; the components of a record may be of different types.

The components of an array are accessed by an index; the components of a record are accessed by a member name.

  1. True
  2. a. 10 b. 3 c. 3 d. 10 e. 30 f. 30 g. row h. row
  3. a.

c. b.

  1. a. enum TeamType {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POST_GRAD}; enum ResultType {WON, LOST, TIED}; b. typedef int Outcome[5][3]; c. Outcome standings; d. standings[FRESHMAN][WON]++;
  2. a. bool arr[5][6]; b. float arr[40][200]; c. char arr[4][16];
  3. a. float arrayA[10][7][21]; b. float arrayB[50][50][128][128];

Programming Warm−up Exercises

  1. void SetFailing( /* inout / bool failing[], / in */ const int score[] )

// Precondition: // score[0..NUM_STUDS−1] are assigned // Postcondition: // For all i, where 0 <= i <= NUM_STUDS−1, // IF score[i] < 60, THEN failing[i] == true

{ int index; // Loop control and index variable

for (index = 0; index < NUM_STUDS; index++)

// (optional) // Invariant (prior to test): // For all i, where 0 <= i <= index−1, // IF score[i] < 60, THEN failing[i] == true // && 0 <= index <= NUM_STUDS

if (score[index] < 60) failing[index] = true; }

  1. int PassTally( /* in */ const bool passing[] )

// Precondition: // passing[0..NUM_STUDS−1] are assigned // Postcondition: // Function value == count of true values // in passing[0..NUM_STUDS−1]

int index; // Loop control and index variable int count = 0; // Count of true values

for (index = 0; index < NUM_STUDS; index++)

col row

col row

col row

3 U U U

return count; }

  1. void Reverse( /* inout */ int score[] )

// Precondition: // score[0..NUM_STUDS−1] are assigned // Postcondition: // score contains the same values as score@entry, // rearranged into reverse order

int index; // Loop control and index variable int tempScore; // Used for swapping int halfLength = NUM_STUDS / 2; // Upper limit for array index

for (index = 0; index < halfLength; index++) { // (optional) // Invariant (prior to test): // For all i, where 0 <= i <= index−1, // score[i] and score[NUM_STUDS − (i + 1)] have // been swapped // && 0 <= index <= halfLength

tempScore = score[index]; score[index] = score[NUM_STUDS − (index + 1)]; score[NUM_STUDS − (index + 1)] = tempScore; } }

Note that if you were to run the loop from 0 to NUM_STUDS instead of NUM_STUDS / 2, the score array would be put back the way it was originally.

// IMPLEMENTATION FILE (intarray.cpp) // This file implements the IntArray class member functions //****************************************************************** #include "intarray.h" #include #include // For exit()

using namespace std;

// Private members of class: // int arr[MAX_SIZE]; // int size;

IntArray::IntArray( /* in */ int arrSize )

// Constructor

// Precondition: // arrSize is assigned // Postcondition: // IF arrSize >= 1 && arrSize <= MAX_SIZE // size == arrSize

// && arr[0..size−1] == 0 // ELSE // Program has halted with error message

int i; // Array index

if (arrSize < 1 || arrSize > MAX_SIZE) { cout << "** In IntArray constructor, invalid size: " << arrSize << " **" << endl; exit(1); } size = arrSize; for (i = 0; i < size; i++) arr[i] = 0; }

int IntArray::ValueAt( /* in */ int i ) const

// Precondition: // i is assigned // Postcondition: // IF i >= 0 && i < size // Function value == arr[i] // ELSE // Program has halted with error message

{ if (i < 0 || i >= size) { cout << "** In ValueAt function, invalid index: " << i << " **" << endl; exit(1); } return arr[i]; }

//******************************************************************

void IntArray::Store( /* in / int val, / in */ int i )

// Precondition: // val and i are assigned // Postcondition: // IF i >= 0 && i < size // arr[i] == val // ELSE // Program has halted with error message

if (i < 0 || i >= size) { cout << "** In Store function, invalid index: " << i << " **" << endl; exit(1);

// (optional) // Invariant (prior to test): // maxSoFar == largest value in arr[0..row−1][0..49] // && 0 <= row <= 50

for (col = 0; col < 50; col++)

// (optional) // Invariant (prior to test): // maxSoFar == largest value in // arr[0..row−1][0..49] and // arr[row][0..col−1] // && 0 <= col <= 50

if (arr[row][col] > maxSoFar) maxSoFar = arr[row][col]; return maxSoFar; }

  1. a. int SchoolMostMoneyFootball( /* in */ const float costOfSports[][NUM_SCHOOLS] )

// Precondition: // costOfSports[FOOTBALL..VOLLEYBALL][0..NUM_SCHOOLS−1] are // assigned // Postcondition: // Function value == i, where costOfSports[FOOTBALL][i] is // the largest value in // costOfSports[FOOTBALL][0..NUM_SCHOOLS−1]

{ int school; // Loop control and index variable int indexOfMax = 0; // Index of max. value in row FOOTBALL

for (school = 1; school < NUM_SCHOOLS; school++)

// (optional) // Invariant (prior to test): // costOfSports[FOOTBALL][indexOfMax] == // largest value in // costOfSports[FOOTBALL][0..school−1] // && 1 <= school <= NUM_SCHOOLS

if (costOfSports[FOOTBALL][school] > costOfSports[FOOTBALL][indexOfMax]) indexOfMax = school; return indexOfMax; }

b. SportType SportMostMoneyLast( /* in */ const float costOfSports[][NUM_SCHOOLS] )

// Precondition: // costOfSports[FOOTBALL..VOLLEYBALL][0..NUM_SCHOOLS−1] are // assigned // Postcondition: // Function value == i, // where costOfSports[i][NUM_SCHOOLS−1] is the largest value

// in costOfSports[FOOTBALL..VOLLEYBALL][NUM_SCHOOLS−1]

{ SportType indexOfMax = FOOTBALL; // Index of max. value in // column NUM_SCHOOLS−

if (costOfSports[BASKETBALL][NUM_SCHOOLS−1] > costOfSports[indexOfMax][NUM_SCHOOLS−1]) indexOfMax = BASKETBALL; if (costOfSports[VOLLEYBALL][NUM_SCHOOLS−1] > costOfSports[indexOfMax][NUM_SCHOOLS−1]) indexOfMax = VOLLEYBALL; return indexOfMax; }

c. int SchoolMostKidsBasketball( /* in */ const int kidsInSports[][NUM_SPORTS] )

// Precondition: // kidsInSports[0..NUM_SCHOOLS−1][FOOTBALL..VOLLEYBALL] are // assigned // Postcondition: // Function value == i, // where kidsInSports[i][BASKETBALL] is the largest value // in kidsInSports[0..NUM_SCHOOLS−1][BASKETBALL]

{ int school; // Loop control and index variable int indexOfMax = 0; // Index of max. value in // column BASKETBALL

for (school = 1; school < NUM_SCHOOLS; school++)

// (optional) // Invariant (prior to test): // kidsInSports[indexOfMax][BASKETBALL] == // largest value in // kidsInSports[0..school−1][BASKETBALL] // && 1 <= school <= NUM_SCHOOLS

if (kidsInSports[school][BASKETBALL] > kidsInSports[indexOfMax][BASKETBALL]) indexOfMax = school; return indexOfMax; }

d. SportType SportMostKidsThird( /* in */ const int kidsInSports[][NUM_SPORTS] )

// Precondition: // kidsInSports[0..NUM_SCHOOLS−1][FOOTBALL..VOLLEYBALL] are // assigned // Postcondition: // Function value == i, // where kidsInSports[2][i] is the largest value // in kidsInSports[2][FOOTBALL..VOLLEYBALL]

SportType indexOfMax = FOOTBALL; // Index of max. value

// Precondition: // FOOTBALL <= whichCol <= VOLLEYBALL // && kidsInSports[0..NUM_SCHOOLS−1][whichCol] are assigned // Postcondition: // Function value == kidsInSports[0][whichCol] + ... // + kidsInSports[NUM_SCHOOLS−1][whichCol]

{ int row; // Loop control and index variable int sum = 0; // Accumulating sum

for (row = 0; row < NUM_SCHOOLS; row++)

// (optional) // Invariant (prior to test): // sum == kidsInSports[0][whichCol] + ... // + kidsInSports[row−1][whichCol] // && 0 <= row <= NUM_SCHOOLS

sum = sum + kidsInSports[row][whichCol]; return sum; }

Given the above ColSum function, here is the solution to part (f):

int TotalKidsInSports( /* in */ const int kidsInSports[][NUM_SPORTS] )

// Precondition: // kidsInSports[0..NUM_SCHOOLS−1][FOOTBALL..VOLLEYBALL] are // assigned // Postcondition: // Function value == sum of all elements of kidsInSports

{ SportType sport; // Loop control and index variable int total = 0; // Total number of kids

for (sport = FOOTBALL; sport <= VOLLEYBALL; sport = SportType(sport + 1)) // (optional) // Invariant (prior to test): // total == sum of all values in columns // FOOTBALL through sport− // && FOOTBALL <= sport <= VOLLEYBALL+

total = total + ColSum(kidsInSports, sport); return total; }

g. The RowSum function of part (e) can be adapted so that it can be used in the following solution. In this new function, named RowSum2, the data types of variables and the initialization and termination of the For loop would need to be changed. The function RowSum2 is not shown here.

int SchoolMostKidsInSports( /* in */ const int kidsInSports[][NUM_SPORTS] )

// Precondition:

// kidsInSports[0..NUM_SCHOOLS−1][FOOTBALL..VOLLEYBALL] are // assigned // Postcondition: // Function value == i, where row i of kidsInSports has // the greatest row sum

int school; // Loop control and index variable int sum; // A row sum int maxSum; // Maximum row sum so far int rowOfMax; // Index of row with maximum sum

maxSum = RowSum2(kidsInSports, 0); rowOfMax = 0; for (school = 1; school < NUM_SCHOOLS; school++) { // (optional) // Invariant (prior to test): // Row rowOfMax has the greatest row sum of // rows 0 through school− // && maxSum == row sum of row rowOfMax // && 1 <= school <= NUM_SCHOOLS

sum = RowSum2(kidsInSports, school); if (sum > maxSum) { maxSum = sum; rowOfMax = school; } } return rowOfMax; }

h. The following solution uses the RowSum function defined in part (e):

SportType SportMostMoney( /* in */ const float costOfSports[][NUM_SCHOOLS] )

// Precondition: // costOfSports[FOOTBALL..VOLLEYBALL][0..NUM_SCHOOLS−1] are // assigned // Postcondition: // Function value == i, where row i of costOfSports has // the greatest row sum

SportType sport; // Loop control and index variable float sum; // A row sum float maxSum; // Maximum row sum so far SportType rowOfMax; // Index of row with maximum sum

maxSum = RowSum(costOfSports, FOOTBALL); rowOfMax = FOOTBALL; for (sport = BASKETBALL; sport <= VOLLEYBALL; sport = SportType(sport + 1)) { // (optional) // Invariant (prior to test): // Row rowOfMax has the greatest row sum of

int store; // Loop control and index variable int month; // Loop control and index variable int dept; // Loop control and index variable

for (store = 0; store < NUM_STORES; store++)

// (optional) // Invariant (prior to test): // sales[0..store−1][0..NUM_MONTHS−1][0..NUM_DEPTS−1] == 0 // && 0 <= store <= NUM_STORES

for (month = 0; month < NUM_MONTHS; month++)

// (optional) // Invariant (prior to test): // sales[store][0..month−1][0..NUM_DEPTS−1] == 0 // && 0 <= month <= NUM_MONTHS

for (dept = 0; dept < NUM_DEPTS; dept++)

// (optional) // Invariant (prior to test): // sales[store][month][0..dept−1] == 0 // && 0 <= dept <= NUM_DEPTS

sales[store][month][dept] = 0; }

  1. void PrintSales( /* in */ const SalesType sales )

// Precondition: // sales[0..NUM_STORES−1][0..NUM_MONTHS−1][0..NUM_DEPTS−1] are // assigned // Postcondition: // Annual sales by department by store have been output

{ int store; // Loop control and index variable int month; // Loop control and index variable int dept; // Loop control and index variable int total; // Total sales for a department

for (store = 0; store < NUM_STORES; store++) { // (optional) // Invariant (prior to test): // Annual sales have been output for each department // of stores 0 through store− // && 0 <= store <= NUM_STORES

cout << "Store " << store; for (dept = 0; dept < NUM_DEPTS; dept++) { // (optional) // Invariant (prior to test): // Annual sales have been output for departments // 0 through dept−1 of store number "store" // && 0 <= dept <= NUM_DEPTS

cout << " Department " << dept; total = 0; for (month = 0; month < NUM_MONTHS; month++)

// (optional) // Invariant (prior to test): // total == sum of values in // sales[store][0..month−1][dept] // && 0 <= month <= NUM_MONTHS

total = total + sales[store][month][dept]; cout << " Total Sales: " << total << endl; } } }

Case Study Follow−Up

  1. The algorithm to compare a list of float values is identical to the algorithm to compare a list of int values. However, the following would have to be changed: the data type of firstList, the data types of the parameters in ReadFirstList and CompareLists, and the data types of the local variables named number in ReadFirstList and CompareLists.
  2. To check for more than MAX_NUMBER values, change the ReadFirstList function as follows:

void ReadFirstList( /* out / int firstList[], // Filled first list / out / int& numVals, // Number of values / inout */ ifstream& dataFile, // Input file / inout / bool& allOK ) // True if list isn’t // too long

// Precondition: // dataFile has been successfully opened for input // Postcondition: // IF more than MAX_NUMBER values were encountered in dataFile // allOK == false // && An error message has been printed // && numVals and contents of firstList are undefined // ELSE // allOK == allOK@entry // && numVals == number of input values in the first list // && numVals <= MAX_NUMBER // && firstList[0..numVals−1] contain the input values

int counter; // Index variable int number; // An input value

counter = 0; dataFile >> number; while (number >= 0 && counter < MAX_NUMBER ) { firstList[counter] = number; counter++; dataFile >> number; }

if (number >=0)

counter = 0; dataFile >> number; while (counter < numVals && dataFile) { if (number != firstList[counter]) { allOK = false; cout << "Position " << counter << ": " << setw(4) << firstList[counter] << " != " << setw(4) << number << endl; } counter++; dataFile >> number; } if (counter < numVals) { // Assert: EOF occurred before first list was finished allOK = false; cout << " Error: First list is longer. " << "Comparison stopped." << endl; } else if (counter == numVals && dataFile) { // Assert: First list has finished but EOF has not occurred allOK = false; cout << "** Error: Second list is longer. " << "Comparison stopped." << endl; }** }

  1. File voteFile is expected to have precinct−candidate pairs, and reading continues until EOF occurs. The program must be tested with different files containing the following data combinations:

· At least one vote for each candidate for each precinct · Exactly one vote for each candidate for each precinct · No votes for candidate 1 in precinct 1, and so on for each candidate and each precinct · An empty file