CS 140 Introduction to Computing I

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

  • Algebra II - Johnston County Schools

    Algebra II - Johnston County Schools

    Unit 5: "Quadratic Functions ... Take half of the coefficient with the x-term and square it. 3.) Add the number found in step 2 to both sides of the equation. 4.) Factor side with variables into a perfect square. 5.)...
  • Sport in our life.

    Sport in our life.

    The players must change positions after each game. The ball must touch the table on both sides of the net each time it is hit. MY FAVOURITE SPORT Rugby Team sport. 15 players in each team. Equipment: an oval ball....
  • Ch. 19-Cattle and Cotton

    Ch. 19-Cattle and Cotton

    Cowboys and the Life on the Trail. Trail crews needed about 12 workers to manage a herd of 2,000 cattle.Wranglers were ranch hands that cared for the crew members' horses.Trail drives began in spring and ended in the fall. Cattle...
  • Discutir el pasado

    Discutir el pasado

    El imperfecto subjuntivo y el pluscuamperfecto subjuntivo. Usen el imperfecto subjuntivo y el pluscuamperfecto subjuntivo cuando el verbo en la cláusula principal está en el pasado y el según verbo es incertidumbre o no es claro. También usen estos tiempos...
  • Introduction to Fundamental Analysis

    Introduction to Fundamental Analysis

    Brain Teasers What is the sum of the numbers between 1 and 50? What is the expected value of a die? Answers 1275: 25 pairs of numbers that each sum to 51 (50+1, 49+2, 48+3…) 3.5 (1/6 + 2/6 +...
  • Ethics Part 2 - University of South Australia

    Ethics Part 2 - University of South Australia

    Three approaches:help to make an ethical choice Ethics as right action. Rules, doing the right thing. deontological, Kantian. Ethics as fairness. Results, doing good, right outcomes
  • Biodiversity of the Peconic River John Buerkel, Brad

    Biodiversity of the Peconic River John Buerkel, Brad

    Biodiversity of the Peconic River. John Buerkel, Brad Governale, Tyler Haug. Mentor: Mr. Robert Bolen. Eastport South Manor Junior Senior High School
  • MINNO® Innovaatioprojekti 2015 - Loppukatselmus

    MINNO® Innovaatioprojekti 2015 - Loppukatselmus

    Minno eli Metropolian Ammattikorkeakoulussa toimiva innovaatiotoimisto. Auttaa yritys- ja erilaisia yhteistyökumppaneita, opettajia, opiskelijoita löytämään toisensa . Palvelu toimii netissä, jossa yhteistyökumppanit voivat tarjota kehittämis- ja projekti-ideoitaan opiskelijoille ja päinvastoin opiskelijat asiantuntemustaan heille