CS 140 Introduction to Computing I

Chapter 7.4 Multidimensional Arrays Goals: To examine the basics of multidimensional arrays in C++ Multidimensional Arrays It is possible to declare arrays of more than one dimension in C++. These arrays are essentially arrays of arrays... double hrsWorked[52][7]; int second[24][60][60]; CS 140 Chapter 11 52 rows & 7 columns, for a total of 364 double values! 24 rows, 60 columns, & 60 layers for a total of 79200 integer values! Page 2 A Simple Example #include using namespace std; void main() { int dozen[3][4] = {11,12,13,14,35,36,37,38,60,70,80,90}; int row; int col; for (row = 0; for (col = { cout << if (col cout else if cout The

initialization of the twodimensional array loads the array one row at a time. row < 3; row++) 0; col < 4; col++) dozen[row][col]; != 3) << " | "; (row != 2) << endl << " | | | " << endl << "---+----+----+---" << endl << " | | | " << endl; } cout << endl << endl; return; } CS 140 Chapter 11 Page 3 A Large Example: Flight Schedules The prototypes may //////////////////////////////////////////////////////////// // This program reads data from an input file regarding a // // list of scheduled flights, and then outputs this data // // in a readable format to the monitor. // //////////////////////////////////////////////////////////// #include #include #include #include using namespace std; const int MAX_NBR_FLIGHTS = 10;

enum CityCode { Atlanta = 1, Chicago, Dallas, Denver, neglect to specify at most one of the dimensions of a multidimensional array parameter. Otherwise, the compiler will be unable to distinguish the dimensions. LosAngeles, NewYork, Seattle }; void loadData(int flightData[][6], int &nbrOfRows); void computeTimes(const int data[][6], int time[], int nbrFlights); int timeChange(CityCode departCity, CityCode arriveCity); void outputChart(const int flyTable[][6], const int minutes[], int nbrRows); void outputFlightInfo(const int flightInfo[], const int minutes); void convertCodeToCity(CityCode city, string cityString); void computeTime(int time, int &hour, int &min, string AMorPM); double computePrice(int nbrMinutes, int nbrMiles); CS 140 Chapter 11 Page 4 // The main function coordinates the retrieval of the flight // // data, the calculation of each flight's time in the air, // // and the output of the flight info in a readable format. // void main() { int numberOfFlights; int flightData[MAX_NBR_FLIGHTS][6]; int elapsedTime[MAX_NBR_FLIGHTS]; loadData(flightData, numberOfFlights); computeTimes(flightData, elapsedTime, numberOfFlights); outputChart(flightData, elapsedTime, numberOfFlights); return; } The main function knows that the flightData array has 10 rows and 6

columns. The loadData function knows that the array has 60 entries and 6 columns, so it deduces that there are 10 rows! // This function loads a two-dimensional array of integers // // with a prepackaged set of data about various flights. // void loadData(int flightData[][6], int &nbrOfRows) { ifstream flightFile; int flightNbr; nbrOfRows = 0; flightFile.open("flightData.txt"); flightFile >> flightNbr; while (!flightFile.eof()) { flightData[nbrOfRows][0] = flightNbr; // Flight Number flightFile >> flightData[nbrOfRows][1]; // Source City Code flightFile >> flightData[nbrOfRows][2]; // Destination City Code flightFile >> flightData[nbrOfRows][3]; // Departure Time (Military) flightFile >> flightData[nbrOfRows][4]; // Arrival Time (Military) flightFile >> flightData[nbrOfRows][5]; // Distance In Miles nbrOfRows++; flightFile >> flightNbr; } return; } CS 140 Chapter 11 Page 5 // This function calculates the total amount of time, in minutes, // // between each flight's takeoff time and its arrival time. This // // data is stored in the parameterized array named time.

// void computeTimes(const int data[][6], int time[], int nbrFlights) { int i, hours, minutes; for (i = 0; i < nbrFlights; i++) { hours = (data[i][4] / 100) - (data[i][3] / 100); if (hours < 0) hours += 24; hours += timeChange(CityCode(data[i][1]), CityCode(data[i][2])); minutes = (data[i][4] % 100) - (data[i][3] % 100); if (minutes < 0) { The integer data in columns 1 minutes += 60; hours--; & 2 of that data array must be } typecast to the enumerated time[i] = 60 * hours + minutes; } CityCode type before being return; } CS 140 passed to the timeChange function. Chapter 11 Page 6 // This function uses a seven-city numerical code to determine the // time difference between two cities, with positive numbers used // for east-to-west flights, and negative numbers for west-to-east // flights. Thus, for example, a NY-to-LA flight yields a result // of 3, while an LA-to-NY flight yields a result of -3. int timeChange(CityCode departCity, CityCode arriveCity) { int departTimeZone, arriveTimeZone; switch(departCity) { case(Atlanta): case(NewYork):

case(Chicago): case(Dallas): case(Denver): case(LosAngeles): case(Seattle): } switch(arriveCity) { case(Atlanta): case(NewYork): case(Chicago): case(Dallas): case(Denver): case(LosAngeles): case(Seattle): } {departTimeZone {departTimeZone {departTimeZone {departTimeZone = = = = 3; 2; 1; 0; break;} break;} break;} break;} {arriveTimeZone {arriveTimeZone {arriveTimeZone {arriveTimeZone = = = = 3; 2; 1; 0;

break;} break;} break;} break;} // // // // // return (departTimeZone - arriveTimeZone); } CS 140 Chapter 11 Page 7 // This function outputs the readable table of flight data to the monitor. // void outputChart(const int flyTable[][6], const int minutes[], int nbrRows) { int flight; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << << << << " "Flight "Number "------ ICARUS AIRLINES FLIGHT SCHEDULE" << endl << endl Departure Departure Arrival Arrival Ticket" << endl City Time City Time Price" << endl

----------------------------------" << endl; for (flight = 0; flight < nbrRows; flight++) outputFlightInfo(flyTable[flight], minutes[flight]); cout << endl << endl; return; } CS 140 The outputFlightInfo function is being sent a single row of the flyTable 2-D array, as well as a single entry of the minutes 1-D array! Chapter 11 Page 8 // This function outputs the flight information in the // parameterized array, using the parameterized integer // value to assist in computing the ticket price. void outputFlightInfo(const int flightInfo[], const int { int hour; int min; string city; string AMorPM[3]; double ticketPrice; cout << ' ' << flightInfo[0] << " // // // minutes) "; convertCodeToCity(CityCode(flightInfo[1]), city); cout << city << setw(14-strlen(city)) << ' '; computeTime(flightInfo[3], hour, min, AMorPM); cout << setw(2) << hour << ':'; (min < 10) ? (cout << '0' << min) : (cout << min); cout << AMorPM; convertCodeToCity(CityCode(flightInfo[2]), city); cout << " " << city << setw(15-strlen(city)) << ' ';

This function is unaware of the fact that its first parameter is actually a row of a 2-D array, and that its second parameter is actually an entry in a 1-D array! computeTime(flightInfo[4], hour, min, AMorPM); cout << setw(2) << hour << ':'; (min < 10) ? (cout << '0' << min) : (cout << min); cout << AMorPM; ticketPrice = computePrice(minutes, flightInfo[5]); cout << " \$" << ticketPrice << endl; return; } CS 140 Chapter 11 Page 9 // This function uses the numerical code associated with a particular // // city to yield the character string representing that city's name. // void convertCodeToCity(CityCode city, string cityString) { switch(city) { case(Atlanta) : {cityString = "Atlanta"; break;} case(Chicago) : {cityString = "Chicago"; break;} case(Dallas) : {cityString = "Dallas"; break;} case(Denver) : {cityString = "Denver; break;} case(LosAngeles): {cityString = "Los Angeles"; break;} case(NewYork) : {cityString = "New York"; break;}

case(Seattle) : {cityString = "Seattle; break;} } return; } // This function uses the military time represented in the parameter time // // to compute the civilian time in hours and minutes, as well as a string // // indicating whether that time is AM or PM. // void computeTime(int time, int &hour, int &min, string AMorPM) { (time < 1200) ? (AMorPM = "AM) : (AMorPM = "PM); hour = ((time/100 - 1) % 12 + 1); min = time % 100; return; } CS 140 Chapter 11 Page 10 // This function computes the price of a flight, using \$2.50 // // per minute or \$0.25 per mile, whichever is more expensive. // double computePrice(int nbrMinutes, int nbrMiles) { double timePrice, distancePrice, price; timePrice = 2.50 * nbrMinutes; distancePrice = 0.25 * nbrMiles; price = (timePrice > distancePrice) ? (timePrice) : (distancePrice); return price; } 1182 7498 9256 3037 6045 3572 4168 7 5 3 1

6 2 4 5 3 1 6 2 4 7 510 807 1250 1620 1854 2101 2319 721 1215 1529 1755 2000 2212 103 1134 1399 822 854 809 1021 1341 Input file flightData.txt Resulting output CS 140 Chapter 11 Page 11

Recently Viewed Presentations

• Welcome to Grade 2 Who am I? Mrs. Leah Kowalczyk This will be my 11th year of teaching in the Calgary Board of Education. With CBE I have taught Kindergarten, Grade 1 and Grade 2 I am excited to continue...
• form the vsepr chart and . is. square. pyramidal. f. render the vespr dot structure of so 4 2-showing the geometry, axe notation and full polarity assessment (molecular and bond polarity…both) step one: calculate valence electrons: s: 7 . ve...
• Justification: Historical Budget Reductions, MAJOR Impacts, View of State of South Dakota budget versus BIA's budget structure, Unable to address SAFETY Standard Issues, Integrate Department of Transportation Performance Management Principles into BIA Road Maintenance Budget, Benefits of a Performance Budget,...
• books this school year between home and school. Although we've also set expectations about trying out a variety of genres to develop their "reading personalities," students will select most of their own books using IPICK. We are finishing up our...
• Islam: Beyond Religion Umayyad (661 - 755) After the death of Muhammad, Abu Bakr became the first Caliph. A caliph is a theocratic ruler, or one who is both a religious leader, and a political leader. He started the idea...
• Bioaccumulation is the gradual build-up of toxic chemicals in living organisms at a faster rate than can be excreted or broken down.. The longer lived organism has more time to accumulate toxins. Eg. Tuna vs minnow. Synthetic Chemicals enter the...
• I recently moved here from Massachusetts where my wife and I were houseparents at a private boarding school. - Todd Macaulay I like to line dance. - Dena Fallen. I love to read and have been in a book club...
• Denise E. Agosto. Drexel University. [email protected] June Abbas. University of Oklahoma. [email protected] This work was supported by a 2014 OCLC/ALISE Library and Information Science Research Grant (LISRG).