Here we use two brackets; one to define the number of rows, and the other to define the number of columns. Similarly, a 2-D array of integers with 3 rows and 4 columns would be defined as:
int x[3][4];
Suppose my grandmother would use
the container with 7 rows and 2 columns to keep her pills. Assume that
the bottom row is used for Sunday, i.e. row 0. Can you tell me, in
terms of rows and columns, where she could get the pill for Tuesday night?
Row: ______ Column:______ OR in an array form:
pill_container[___][___]?
Now let's write a program that uses a 2-D arrays.
//P9_3.cpp - This program will ask a runner for her/his fastest 5 times
for 6
// different distances and will display them using a 2-D array.
#include<iostream>
using namespace std;
int find_distance(int j); //a function that returns a distance based on the choice j
int main( )
{
int i =0;
int distance[6];
double data[6][5]; //This array will keep 30 values
in 6 rows and 5 columns
// 6 events and 5 times for each one of the events
for(int j = 0; j < 6; j++)
{
distance[j] = find_distance(j);
cout << "\nEnter 5 of your
best running times for \n " << distance[j] << " m \n";
for(int i = 0; i < 5; i++)
{
cout << "Enter
a time \n";
cin >> data[j][i];
}
}
cout << "Here is your best 5 times: ";
for(int j = 0; j < 6; j++)
{
cout << "\nDistance
: " << distance[j] << " m \n";
for(int i = 0; i <
5; i++)
{
cout <<
data[j][i] << "\t";
}
cout << endl;
}
return 0;
}
int find_distance(int j)
{
switch (j)
{
case 0: // 100 meter
return 100;
break;
case 1: // 150 meter
return 150;
break;
case 2: // 200 meter
return 200;
break;
case 3: // 400 meter
return 400;
break;
case 4: // 500 meter
return 800;
break;
default: // 1600 meter
return 1600;
}
}
In the above program, we can access the 3rd time of the 4th event (400 m) in:
data[3][2]; // note that the 3rd time is stored in column with
index 2
// and the 4th event is stored in row with index 3
The 4th event was 400 meter.
To access the 5 times for 150 m event, we can use:
data[1][0], data[1][1], data[1][2], data[1][3], data[1][4]
Or use a for loop to access them:
for(int i = 0; i < 5; i++)
data[1][i];
Exercise 9.5
Modify the above program such that it finds the best, the worst, and
the average time for each of the six events. The program should display,
for each event, all five times, the worst, the best, and the average.
Call your program ex95.cpp.