Multidimensional Arrays in C++

You can create an array of any dimension in C++.

Pornt In the preceding section, you used a two-dimensional array to represent a matrix or a table. Occasionally, you will need to represent n-dimensional data structures. In C++, you can create n-dimensional arrays for any integer n.

Declaring a two-dimensional array can be generalized to declaring an n-dimensional array for n > = 3. For example, you may use a three-dimensional array to store exam scores for a class of six students with five exams and each exam has two parts (multiple-choice and essay). The following syntax declares a three-dimensional array variable scores.

double scores[6][5][2];

You can also use the short-hand notation to create and initialize the array as follows:

double scores[6][5][2] = {

{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},

{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},

{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},

{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},

{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},

{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};

scores[0][1][0] refers to the multiple-choice score for the first student’s second exam, which is 9.0. scores[0][1][1] refers to the essay score for the first student’s second exam, which is 22.5. This is depicted in the following figure:

1. Problem: Daily Temperature and Humidity

Suppose a meteorology station records the temperature and humidity at each hour of every day and stores the data for the past 10 days in a text file named weather.txt (see www.cs.armstrong .edu/liang/data/Weather.txt). Each line of the file consists of four numbers that indicate the day, hour, temperature, and humidity. The contents of the file may appear as in (a):

Note that the lines in the file are not necessary in order. For example, the file may appear as shown in (b).

Your task is to write a program that calculates the average daily temperature and humid­ity for the 10 days. You can use the input redirection to read the data from the file and store them in a three-dimensional array, named data. The first index of data in the range from 0 to 9 represents 10 days, the second index from 0 to 23 represents 24 hours, and the third index from 0 to 1 represents temperature and humidity, respectively. Note that the days are numbered from 1 to 10 and hours are numbered from 1 to 24 in the file. Since the array index starts from 0, data[0][0][0] stores the temperature in day 1 at hour 1 and data[9][23][1] stores the humidity in day 10 at hour 24.

The program is given in Listing 8.5.

Listing 8.5 Weather.cpp

1 #include <iostream>
2
using namespace std;
3
4
int main()
5 {

6    const int NUMBER_OF_DAYS = 10;
7   
const int NUMBER_OF_HOURS = 24;
8   
double data[NUMBER_OF_DAYS][NUMBER_OF_HOURS][2];
9
10   
// Read input using input redirection from a file
11    int day, hour;
12   
double temperature, humidity;
13   
for (int k = 0; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++)
14    {
15       cin >> day >> hour >> temperature >> humidity;
16       data[day –
1][hour – 1][0] = temperature;
17       data[day –
1][hour – 1][1] = humidity;
18    }
19
20   
// Find the average daily temperature and humidity
21    for (int i = 0; i < NUMBER_OF_DAYS; i++)
22    {
23       
double dailyTemperatureTotal = 0, dailyHumidityTotal = 0;
24       
for (int j = 0; j < NUMBER_OF_HOURS; j++)
25       {
26          dailyTemperatureTotal += data[i][j][
0];
27          dailyHumidityTotal += data[i][j][
1];
28       }
29
30     
// Display result
31      cout << “Day ” << i << “‘s average temperature is ”
32      << dailyTemperatureTotal / NUMBER_OF_HOURS << endl;
33      cout <<
“Day ” << i << “‘s average humidity is ”
34      << dailyHumidityTotal / NUMBER_OF_HOURS << endl;
35    }
36
37   
return 0;
38 }

You can use the following command to compile the program:

g++ Weather.cpp -o Weather

Use the following command to run the program:

Weather.exe < Weather.txt

A three-dimensional array data is declared in line 8. The loop in lines 13-18 reads the input to the array. You could enter the input from the keyboard, but it would be awkward. For conven­ience, we store the data in a file and use the input redirection to read the data from the file. The loop in lines 24-28 adds all temperatures for each hour in a day to dai l yTemperatureTotal and all humidity for each hour to dail yHumidityTotal. The average daily temperature and humidity are displayed in lines 31-34.

2. Problem: Guessing Birthdays

Listing 4.4, GuessBirthday.cpp, gives a program that guesses a birthday. The program can be simplified by storing the numbers in five sets in a three-dimensional array and prompting the user for the answers using a loop, as shown in Listing 8.6.

Listing 8.6 GuessBirthdayUsingArray.cpp

1 #include <iostream>
2
#include <iomanip>
3
using namespace std;
4
5
int main()
6 {
7   
int day = 0; // Day to be determined
8    char answer;
9
10   
int dates[5][4][4] = {
11      {{
1, 3, 5, 7},
12       {
9, 11, 13, 15},
13       {
17, 19, 21, 23},
14       {
25, 27, 29, 31}},
15      {{
2, 3, 6, 7},
16       {
10, 11, 14, 15},
17       {
18, 19, 22, 23},
18       {
26, 27, 30, 31}},
19      {{
4, 5, 6, 7},
20       {
12, 13, 14, 15},
21       {
20, 21, 22, 23},
22       {
28, 29, 30, 31}},
23      {{
8, 9, 10, 11},
24       {
12, 13, 14, 15},
25       {
24, 25, 26, 27},
26       {
28, 29, 30, 31}},
27      {{
16, 17, 18, 19},
28       {
20, 21, 22, 23},
29       {
24, 25, 26, 27},
30       {
28, 29, 30, 31}}};
31
32   
for (int i = 0; i < 5; i++)
33    {
34       cout <<
“Is your birthday in Set” << (i + 1) << “?” << endl;
35       
for (int j = 0; j < 4; j++)
36       {
37         
for (int k = 0; k < 4; k++)
38          cout << setw(
3) << dates[i][j][k] << ” “;
39          cout << endl;
40       }
41       cout <<
“\nEnter N/n for No and Y/y for Yes: “;
42       cin >> answer;
43       
if (answer == ‘Y’ || answer == ‘y’)
44       day += dates[i][
0][0];
45    }
46
47    cout <<
“Your birthday is ” << day << endl;
48
49   
return 0;
50 }

A three-dimensional array dates is created in lines 10-30. This array stores five sets of numbers. Each set is a 4-by-4 two-dimensional array.

The loop starting from line 32 displays the numbers in each set and prompts the user to answer whether the day is in the set (lines 37-38). If it is, the first number (dates[i][0]) in the set is added to variable day (line 44).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *