Using Multidimensional Arrays

The power of an array can be greatly increased by creating multidimensional arrays: an array whose element values are also arrays. This concept is tough to visualize (it's roughly equivalent to a stack of two-column tables) but not that hard to use.

All of the same rules for arrays apply to multidimensional arrays. Once again you'll use the square brackets to indicate the number of elements. This time you'll do so twice:

float grades[3][20];

The first number indicates the number of subarrays (or tables, in layman's terms) the main array contains. The second number specifies the number of rows each subarray (table) contains.

Populating multidimensional arrays is also tricky. You first refer to the subarray index and then the index for that subarray. So the first element in the first subarray would be at grades[0][0]. The tenth element in the third subarray is at grades[2][9].

Again, you can populate an entire multidimensional array in one step using the curly braces. With a multidimensional array, you'll need to use one set of curly braces for each subarray, with each separated by a comma and the entire construct within another pair of curly braces (for the main array):

int grades [][] {
{84, 72, 91, 88},
{65, 68, 94, 96},
{75, 91, 82, 82},
}

The preceding code creates a multidimensional array containing three subarrays, each of which has four elements. Notice that by spacing the assignment out over several lines it's more legible.

You can use loops with multidimensional arrays, but to access every element, you'll need two loops: an outer loop to access the main array's elements (which are also arrays), and an inner loop to access every element of each subarray. Let's rewrite the exchange application using a multidimensional array.

To use multidimensional arrays

1.
Open exchange2.c (Script 6.5) in your text editor or IDE, if it is not already open.

2.
Turn the amounts array into a multidimensional double (Script 6.7):

double amounts[2][NUM];

Script 6.7. This final version of the exchange rate conversion application uses three different multidimensional arrays.


In its previous incarnation, amounts was a simple array of floats. Now it will contain two subarrays, each of which is NUM elements long. Every value stored in the array will be a double.

3.
Store the data table column headers as a multidimensional array:

char titles[2][6] = {
     {"Pesos"},
     {"Euros"}
};

This application uses a second multidimensional array, called titles. This array contains essentially two strings—Pesos and Euros—but creating strings requires a character array. The titles array will be used to create the table column headings for the output (Figure 6.12).

Figure 6.12. Two tables of currency conversions are created using three multidimensional arrays.


4.
Store the conversion rates in a simple array:

double rates[] = {11.317466,
 0.823859};

Rather than hardcoding these numbers in the code, we will store them in a variable as well. Maintaining the same structure created in Step 3, the array's first element corresponds to pesos and the second to euros.

5.
Add a second loop variable:

unsigned int i, j;

Because multidimensional arrays often require two loops, two separate index variables are needed for these loops. Keeping with standard C practices, i will be used in the outermost loop and j in the inner loop.

6.
Alter the main application statement:

printf ("US Dollar amounts converted
 to Mexican Pesos and Euros:

");

The caption should now indicate that the output reflects conversion into both pesos and euros.

7.
Create the first loop:

for (i = 0; i < 2; i++) {

This first loop will be used to access the primary arrays: amounts, titles, and rates. Each of those was defined with two elements, so this loop counts from 0 to 1 (i < 2).

8.
Add the table header print statement:

printf ("%10s %10s
", "Dollars",
 titles[i]);

This header text is exactly like it was in the previous examples except that now the second column heading (pesos or euros) will be pulled from the titles array.

9.
Add another loop that prints every calculation:

for (j = 0; j < NUM; j++) {
  amounts[i][j] = (j + 1) * 5.00;
  printf ("%10.2f %10.2f
",
 amounts[i][j], (amounts[i][j]
 * rates[i]));
 }

This loop is almost exactly like the original loop in the previous version of the exchange application. The first key difference is that this loop refers to amounts[i][j] instead of just amounts[i] in order to access the scalar values of the multidimensional array.

A second difference here is that the rates array is used for determining the conversion rate for the respective currency.

Aside from those two changes, the functionality remains the same. Again, the initial dollar value is calculated in increments of 5 and assigned to the array. This then is used in making calculations and printing the amounts.

10.
Complete the formatting and the outer loop:

    printf ("

");
} // End of outer for loop.

When using complex, nested loops, it's increasingly important to comment on where they end so that you understand what braces in your code are doing.

11.
Save the file as exchange3.c, compile, and debug as necessary.

12.
Run the application to see the results (Figure 6.12).

13.
Change the value of NUM, recompile, and rerun the application (Figure 6.13).

Figure 6.13. Despite the more complex nature of the application—relying heavily on multidimensional arrays—changing the value of NUM creates different-length lists of data.


✓ Tips

  • Once again, the amounts array is underutilized here, having been assigned values that are never later used. Still, the example demonstrates a concept well, and you could add to the application so that amounts is used again.

  • Through C libraries you can use different array-related functions, like qsort(), a common and powerful sorting algorithm. See Appendix B, “Resources,” to learn where you can find out more.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset