Notes_10 - Chapter 10 Arrays Goals: To introduce the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 10 Arrays Goals: To introduce the concept of array variables To demonstrate how forloops are used to traverse arrays To explain how arrays are stored in RAM To illustrate how arrays can be initialized in C++ To demonstrate how arrays can be used as parameters To examine common array operations (sorting & searching) Array Variables When dealing with several values of the same type, which are used for similar purposes within a program, it is often convenient to use a single variable to hold the values. int hourlyReading[24]; This variable declaration reserves space in RAM for 24 integer values, which are referred to within the program as hourlyReading[0] through hourlyReading[23]. CS 140 Chapter 9 Page 2 #include <iostream> #include <iomanip> using namespace std; void main() { int hourlyReading[24]; int i; for (i = 0; i < 24; i++) { cout << setw(2) << (i % 12 + 1) << " o\'clock reading: " << hourlyReading[i]; if (i % 3 == 2) cout << endl; else cout << '\t'; } for (i = 0; i < 24; hourlyReading[i] hourlyReading[3] = hourlyReading[7] = hourlyReading[9] = hourlyReading[12] = hourlyReading[20] = hourlyReading[23] = i++) = -1; 300; 700; 900; 1200; 2000; 2300; Notice that the first value in the array is indexed at 0, not 1! One value in the array may be output, but not the whole array at once! Assignment statements may be used with one cout << endl << endl; for (i = 0; i < 24; i++) value in the array, but not with the whole array! { cout << setw(2) << (i % 12 + 1) << " o\'clock reading: " << setw(4) << hourlyReading[i]; if (i % 3 == 2) cout << endl; else cout << '\t'; } cout << endl; CS 140 } Chapter 9 Page 3 #include <iostream> #include <iomanip> #include <fstream> using namespace std; void main() { double highVal[10]; double newVal; int lowValIndex; int nbrOfVals = 0; int i; ifstream valFile; valFile.open("values.txt"); valFile >> newVal; while (!valFile.eof()) { if (nbrOfVals < 10) { highVal[nbrOfVals] = newVal; nbrOfVals++; } else { lowValIndex = 0; for (i = 0; i < 10; i++) if (highVal[i] < highVal[lowValIndex]) lowValIndex = i; if (newVal > highVal[lowValIndex]) highVal[lowValIndex] = newVal; } valFile >> newVal; } valFile.close(); cout << setw(20) << "Highest Values" << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(5); for (i = 0; i < nbrOfVals; i++) cout << setw(17) << highVal[i] << endl; cout << endl; return; } 98.64537 98.55201 98.60001 98.67235 98.99209 99.00128 98.66297 98.71102 98.82376 98.34278 96.78349 98.06629 98.81553 96.82326 99.00189 97.00226 98.63230 98.25172 97.80251 97.12194 Contents of values.txt Resulting Output CS 140 Chapter 9 Page 4 0 1 2 3 4 5 6 7 8 9 CS 140 98.64537 ? 99.00128 ? 98.81553 96.78349 ? 98.82376 98.25172 97.00226 ? 98.99209 98.55201 ? 98.66297 ? 98.06629 ? 98.67235 98.63230 ? 98.60001 ? 99.00189 98.71102 ? 98.64537 98.55201 98.60001 98.67235 98.99209 99.00128 98.66297 98.71102 98.82376 98.34278 96.78349 98.06629 98.81553 96.82326 99.00189 97.00226 98.63230 98.25172 97.80251 97.12194 If the array isn't already full (i.e., if nbrOfVals does not equal 10), then just insert at the end of the list! If the array is already full, then find the smallest entry in the array and, if it's smaller than the new value, do a replacement! Chapter 9 Page 5 What's Happening in Memory? When an array variable is declared, the size of the array and the number of bytes required for one variable of the designated type are multiplied. The product is the number of consecutive bytes allocated for the array variable. int weekdayTotal[5]; char password[12]; RAM we ek d m ayT em ot or al y 's 4 bytes per int; 20 bytes total 1 byte per char; 12 bytes total CS 140 Chapter 9 pa s m swo em rd or 's y Page 6 Improper Indexing The compiler will not detect a problem when an array is indexed improperly, but an error may occur during execution! #include <iostream> #include <iomanip> #include <cmath> using namespace std; void main() { int twoPower[30]; int i; for (i = 0; i <= 30; i += 1) { twoPower[i] = int(pow(2,i)); cout << setw(2) << i << ": "; cout << twoPower[i] << endl; } return; } CS 140 Chapter 9 Page 7 More Improper Indexing It's possible that no error will be detected, even during execution. But that still doesn't mean that the program will work! #include <iostream> #include <iomanip> #include <cmath> using namespace std; void main() { int nbr = 0; int twoPower[6]; int i; for (i = 0; i <= 6; i += 1) { twoPower[i] = int(pow(2,i)); cout << setw(2) << i << ": "; cout << twoPower[i] << endl; cout << "nbr equals: " << nbr << endl << endl; } return; } Notice how the nbr variable got assigned a new value by mistake? Apparently, nbr is being held in the RAM position right after the last entry in the twoPower array. Since the system sees that that memory is being used by the program, it doesn't object to loading it with a value! CS 140 Chapter 9 Page 8 Array Initialization #include <iostream> #include <iomanip> using namespace std; void main() { int firstIntList[10] = {0}; int otherIntList[10] = {7}; int thirdIntList[10] = {5,4,3,2}; int finalIntList = {0,1,2,3,4,5,6,7,8,9}; double firstDubList[10] = {0.0}; double finalDubList[10] = {1.2, 2.3, 3.4, 4.5, 5.6}; char firstCharList[10] = {'X'}; char finalCharList[10] = {'A','E','I','O','U'}; int i; 1 While assignment operators cannot normally be used to assign values to entire arrays, they can be used to initialize arrays when they're being declared. 2 cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); 1) If the array size is specified and the number of initialized values is too low, all remaining slots are filled with zeroes. 2) If the array size is unspecified, then it's set to the number of initialized values. CS 140 for (i = 0; i cout << << << << << << << << < 10; i++) setw(2) << setw(2) << setw(2) << setw(2) << setw(5) << setw(5) << setw(2) << setw(2) << firstIntList[i] otherIntList[i] thirdIntList[i] finalIntList[i] firstDubList[i] finalDubList[i] firstCharList[i] finalCharList[i] << endl; cout << endl; return; } Chapter 9 Page 9 Passing Array Entries to Functions Array entries may be passed to functions by value or by reference, just like regular variables. #include <iostream> #include <iomanip> #include <fstream> using namespace std; const double MAX_GROSS = 400.00; double skim(double &gross); void main() { double grossList[365]; ifstream grossFile; ofstream newGrossFile; double embezzlement = 0.0; int i; grossFile.open("GrossFile.txt"); for (i = 0; i < 365; i++) grossFile >> grossList[i]; grossFile.close(); } newGrossFile.open("GrossFile.txt"); newGrossFile.setf(ios::fixed); newGrossFile.setf(ios::showpoint); newGrossFile.precision(2); for (i = 0; i < 365; i++) { embezzlement += skim(grossList[i]); newGrossFile << grossList[i]; if (i % 10 == 9) newGrossFile << endl; else newGrossFile << " "; } newGrossFile.close(); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Amount embezzled: $" << embezzlement << endl << endl; return; double skim(double &gross) { double skimAmt = 0.0; if (gross > MAX_GROSS) { skimAmt = gross - MAX_GROSS; gross = MAX_GROSS; } return skimAmt; } Since the parameter was passed by reference, the alterations are actually being made to the value in the array! Page 10 CS 140 Chapter 9 Original contents of GrossFile.txt: 804.89 405.49 124.58 843.20 173.52 133.97 885.58 590.91 583.82 928.43 692.45 351.50 544.82 229.25 207.94 582.64 114.42 531.67 445.84 465.61 614.39 152.51 291.35 766.33 306.04 439.77 907.91 283.88 350.40 984.07 760.26 606.81 822.71 964.90 365.12 912.91 747.27 354.00 464.60 222.49 541.53 198.79 987.64 803.19 305.00 547.71 239.85 363.00 788.99 624.66 229.55 127.55 550.15 845.54 652.27 767.07 769.38 129.22 512.66 954.82 869.49 537.19 819.56 705.38 828.21 991.46 546.80 607.69 206.73 382.64 363.20 226.56 124.09 165.28 645.89 607.22 730.13 605.27 141.80 171.96 394.89 807.91 112.00 950.95 685.33 263.36 432.30 726.15 969.18 922.96 601.68 701.57 Final contents of GrossFile.txt: 400.00 400.00 124.58 400.00 173.52 133.97 400.00 400.00 400.00 400.00 400.00 351.50 400.00 229.25 207.94 400.00 114.42 400.00 400.00 400.00 400.00 152.51 291.35 400.00 306.04 400.00 400.00 283.88 350.40 400.00 400.00 400.00 400.00 400.00 365.12 400.00 400.00 354.00 400.00 222.49 400.00 198.79 400.00 400.00 305.00 400.00 239.85 363.00 400.00 400.00 229.55 127.55 400.00 400.00 400.00 400.00 400.00 129.22 400.00 400.00 400.00 400.00 400.00 400.00 400.00 400.00 400.00 400.00 206.73 382.64 363.20 226.56 124.09 165.28 400.00 400.00 400.00 400.00 141.80 171.96 394.89 400.00 112.00 400.00 400.00 263.36 400.00 400.00 400.00 400.00 400.00 400.00 CS 140 Chapter 9 Page 11 Another Example #include <iostream> using namespace std; const int LIST_SIZE = 10; bool isPowerOfTwo(int value); Setting up a constant for the array size simplifies code modification if a different size is needed later. void main() { int favoriteNbr[LIST_SIZE] = {13,16,21,29,32,35,50,75,95,100}; int i; int powerOfTwoCount = 0; for (i = 0; i < LIST_SIZE; i++) { if (isPowerOfTwo(favoriteNbr[i])) powerOfTwoCount++; } cout << "The List:" << endl; for (i = 0; i < LIST_SIZE; i++) cout << favoriteNbr[i] << endl; cout << endl << powerOfTwoCount << " are powers of two!" << endl << endl; Since the parameter was passed by value, the alterations are made to the value of the copy, not to the value in the array! CS 140 return; } bool isPowerOfTwo(int value) { while ((value % 2 == 0) && (value > 1)) value /= 2; return (value == 1); } Chapter 9 Page 12 Passing An Entire Array To A Function An entire array may be passed to a function as a parameter, but only the memory location of the array is actually passed. Thus, an array cannot be passed by value; it is essentially passed by reference, but without the ampersand marking it as passedbyreference. Each function prototype with an array //////////////////////////////////////////////////////brackets to specify that it's an array, but // This program retrieves a list of test scores // // from a user-specified input file. These scores //since the parameter is essentially passed // are sorted and averaged. Output includes the // by reference, its size need not be specified // presorted and sorted lists, as well as the mean. // here. ////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include <fstream> #include <cassert> using namespace std; const int MAX_LIST_SIZE = 50; void inputList(int list, int &listSize); void outputList(const int list, int listSize); void sortList(int list, int listSize); double averageList(const int list, int listSize); CS 140 Chapter 9 parameter must specify the type and use Since array parameters cannot be passed by value, there is a danger that they might be inadvertently altered within a function. To avoid this, they can be modified with the const designation, which prohibits the function from changing their values. Page 13 // The main function supervises the input, output, // // sorting, and averaging of a list of test scores, // // including the output of the list's mean value. // void main() { int testScore[MAX_LIST_SIZE]; int nbrStudents; inputList(testScore, nbrStudents); cout << endl << "Presorted Scores:" << endl; outputList(testScore, nbrStudents); sortList(testScore, nbrStudents); cout << endl << "Sorted Scores:" << endl; outputList(testScore, nbrStudents); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << endl << "The mean score is " << averageList(testScore, nbrStudents) << endl << endl; return; } When actually calling the function, the type of the array parameter is not specified in the function call. Similarly, the square brackets designating the argument as an array and the size of the array are not specified in the function call. CS 140 Chapter 9 Page 14 // This function fills an array with the contents of a user- // // specified input file, stopping at the end of the file or // // the capacity of the array, whichever comes first. // void inputList(int list, int &listSize) Notice that a character string is just { ifstream inputFile; another type of array. char inputFileName[MAX_LIST_SIZE]; (We'll see more details in the next int value; cout << "Enter the name of the input file: "; cin >> inputFileName; inputFile.open(inputFileName); assert(!inputFile.fail()); chapter.) listSize = 0; inputFile >> value; while ((!inputFile.eof()) && (listSize < MAX_LIST_SIZE)) { list[listSize] = value; listSize++; inputFile >> value; As long as there are more values in } the input file AND more room in the inputFile.close(); return; } array being filled, this loop keeps getting new entries for the array. CS 140 Chapter 9 Page 15 // This function outputs the parameterized list, // // placing at most ten values on each output line. // void outputList(const int list, int listSize) { int i; } for (i = 0; i < listSize; i++) { cout << setw(3) << list[i]; if (i % 10 == 9) // This function performs an "insertion sort" on the parameterized cout << endl; // array, sorting its entries by assuming that the first k entries else // are already sorted, and then inserting the (k+1)-st entry where cout << " "; // it belongs in that sorted k-sublist. } void sortList(int list, int listSize) cout << endl; { int currentIndex; return; int backIndex; int currentValue; for (currentIndex = 1; currentIndex < listSize; currentIndex++) { currentValue = list[currentIndex]; backIndex = currentIndex - 1; while ((backIndex >= 0) && (list[backIndex] > currentValue)) { list[backIndex + 1] = list[backIndex]; backIndex--; } list[backIndex + 1] = currentValue; } return; } Notice that the array elements may be used, but not altered in this function. This is because of the const modifier of the list parameter. // // // // Since the sorted array is needed in the main function, no const modifier is employed in this function. Essentially, this nested loop keeps "sliding" array entries over until it finds the slot where currentValue belongs. Chapter 9 Page 16 CS 140 // This function computes the arithmetic mean of the values in // // the parameterized array, returning this mean value to the // // calling function. Zero is returned if the array is empty. // double averageList(const int list, int listSize) { int sum = 0; int i; Again, this function shouldn't be altering the if (listSize == 0) return 0; else { for (i = 0; i < listSize; i++) sum += list[i]; return double(sum)/listSize; } } array's contents, so a const modifier is used. Contents of exam1.txt: 98 49 97 88 76 93 CS 140 64 90 90 55 68 42 53 69 62 92 36 78 91 85 83 51 78 91 28 52 30 72 51 89 67 96 80 65 89 71 83 62 71 92 92 29 Chapter 9 Page 17 An Alternative Sorting Algorithm // This function performs an "selection sort" on the parameterized // array, sorting its entries by finding the smallest entry and // swapping it with the first entry, then finding the next smallest // entry and swapping it with the second entry, and so forth. void sortList(int list, int listSize) { int index; int currentIndex; int smallestIndex; int temp; // // // // Many sorting algorithms have been developed. In addition to the insertion sort we've already seen, there is a selection sort: Notice that the function's name and parameter list are identical with what was used in the previous example. The principles of information hiding are thus upheld, and this new sorting algorithm can replace the old one with no other changes to the program! } for (currentIndex = 0; currentIndex < listSize - 1; currentIndex++) { smallestIndex = currentIndex; for (index = currentIndex + 1; index < listSize; index++) if (list[index] < list[smallestIndex]) smallestIndex = index; if (smallestIndex != currentIndex) { temp = list[currentIndex]; Essentially, this nested loop list[currentIndex] = list[smallestIndex]; list[smallestIndex] = temp; keeps finding the kth smallest } entry and swapping it with what's } return; in array slot #(k1). CS 140 Chapter 9 Page 18 Searching An Unsorted Array The most common algorithm for searching for a particular value within an unsorted array is the sequential search: // // // // // // This function performs a sequential search of the parameterized // array for the parameterized value. Starting at the top of the // array, it examines each entry, returning a boolean value of true // as soon as it finds the value, or a boolean value of false if it // traverses the entire array without locating the value. bool searchList(const int list, int listSize, int soughtValue) { int i; for (i = 0; i < listSize; i++) if (list[i] == soughtValue) return true; return false; } Because the number of comparisons executed in this algorithm is, on average, directly proportional to the number of elements in the array, this algorithm is also known as a linear search. Chapter 9 Page 19 CS 140 // This function performs a binary search of the parameterized // // array for the parameterized value. Starting at the middle // // of the array, it compares that entry to the sought value, // // returning a boolean value of true if they're equal, but // // eliminating the first half of the list from any further // // consideration if the middle value is too small or the second // // half if the middle value is too large. It continues halving // // the list until it actually finds the sought value, in which // // case it returns a boolean value of true, or until it // // eliminates the entire array from consideration, in which it // // returns a boolean value of false. // bool searchList(const int list, int listSize, int soughtValue) { int lowIndex = 0; int highIndex = listSize -1; int middleIndex; while (lowIndex <= highIndex) { middleIndex = (lowIndex + highIndex) / 2; if (list[middleIndex] == soughtValue) return true; else if (list[middleIndex] < soughtValue) lowIndex = middleIndex + 1; else highIndex = middleIndex - 1; } return false; } Searching A Sorted Array The most common algorithm for searching for a particular value within a sorted array is the binary search. Notice that the number of comparisons executed in this algorithm is, on average, directly proportional to the base2 logarithm of the number of elements in the array. Chapter 9 Page 20 CS 140 ...
View Full Document

Ask a homework question - tutors are online