Understanding Multidimensional Arrays in C++
This chapter delves into the fundamentals of multidimensional arrays in C++. It highlights how these arrays function as arrays of arrays, showcasing examples with two-dimensional and three-dimensional arrays. Through practical examples, such as loading flight schedules, readers will learn how to declare, initialize, and manipulate multidimensional arrays. The chapter emphasizes the significance of correct dimensional specification to avoid compilation errors and demonstrates the use of enumerated types for better code readability.
Understanding Multidimensional Arrays in C++
E N D
Presentation Transcript
Chapter 7.4Multidimensional 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... 52 rows & 7 columns, for a total of 364 double values! double hrsWorked[52][7]; 24 rows, 60 columns, & 60 layers for a total of 79200 integer values! int second[24][60][60]; CS 140
A Simple Example The initialization of the two-dimensional array loads the array one row at a time. #include <iostream> 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; row < 3; row++) for (col = 0; col < 4; col++) { cout << dozen[row][col]; if (col != 3) cout << " | "; else if (row != 2) cout << endl << " | | | " << endl << "---+----+----+---" << endl << " | | | " << endl; } cout << endl << endl; return; } CS 140
A Large Example: Flight Schedules The prototypes may neglect to specify at most one of the dimensions of a multidimensional array parameter. Otherwise, the compiler will be unable to distinguish the dimensions. //////////////////////////////////////////////////////////// // 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 <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; const int MAX_NBR_FLIGHTS = 10; enum CityCode { Atlanta = 1, Chicago, Dallas, Denver, 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
// 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; } // 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; } 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! CS 140
// 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) { minutes += 60; hours--; } time[i] = 60 * hours + minutes; } return; } The integer data in columns 1 & 2 of that data array must be typecast to the enumerated CityCode type before being passed to the timeChange function. CS 140
// 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): {departTimeZone = 3; break;} case(Chicago): case(Dallas): {departTimeZone = 2; break;} case(Denver): {departTimeZone = 1; break;} case(LosAngeles): case(Seattle): {departTimeZone = 0; break;} } switch(arriveCity) { case(Atlanta): case(NewYork): {arriveTimeZone = 3; break;} case(Chicago): case(Dallas): {arriveTimeZone = 2; break;} case(Denver): {arriveTimeZone = 1; break;} case(LosAngeles): case(Seattle): {arriveTimeZone = 0; break;} } return (departTimeZone - arriveTimeZone); } CS 140
// 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 << " ICARUS AIRLINES FLIGHT SCHEDULE" << endl << endl << "Flight Departure Departure Arrival Arrival Ticket" << endl << "Number City Time City Time Price" << endl << "------ --------- --------- ------- ------- ------" << endl; for (flight = 0; flight < nbrRows; flight++) outputFlightInfo(flyTable[flight], minutes[flight]); cout << endl << endl; return; } 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! CS 140
// 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 minutes) { int hour; int min; string city; string AMorPM[3]; double ticketPrice; cout << ' ' << flightInfo[0] << " "; 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)) << ' '; 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; } 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! CS 140
// 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
// 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 7 5 510 721 1134 7498 5 3 807 1215 1399 9256 3 1 1250 1529 822 3037 1 6 1620 1755 854 6045 6 2 1854 2000 809 3572 2 4 2101 2212 1021 4168 4 7 2319 103 1341 Input file flightData.txt Resulting output CS 140