Wednesday, 17 December 2014

// The "MultiDimensionalArraysExample5" class.  Page 322-323.
//  (from the Carter book)
//
// Example 5: 

// 1. The following fragment could be used to find the
// sum of the elements of a ragged 2-dimensional array,
// like the one shown in Example 4.  Notice that the upper
// bound of the inner for loop now depends on the length
// of each row of the array, as they each differ in length
// First, re-declare the "ragged" array here for this
// example.

public class MultiDimensionalArraysExample5
{
    public static void main (String[] args)
    {
        int[] [] ragged = {{4, 3, 7},
                {5, 2},
                {7, 8, 1, 4}};

        int sum = 0;

        for (int row = 0 ; row < ragged.length ; row++)
        {
            for (int col = 0 ; col < ragged [row].length ; col++)
            {
                // sum up the elements in each row of the
                // "ragged" array --> the "col" value (length)
                // is different for each row
                sum += ragged [row] [col];
                System.out.print (ragged [row] [col] + " ");
                System.out.print (" += ");
                System.out.println (sum);
            } // end of inner for loop
        } // end of outer for loop

    } // main method
} // MultiDimensionalArraysExample5 class
//
// Example 5: (continued):
//
// 2. Multi-dimensional arrays are NOT limited to only 2 dimensions.
// We can create 3-dimensional arrays, 4-dimensional arrays, or arrays of
// even higher dimensions.  These higher-dimensional arrays are usually
// rectangular, but they need not be.
// 3. We suggested that a 2-dimensional rectangular array could be visualized
// as a table with rows and columns.  Similarly, a rectangular 3-dimensional
// array could be visualized as a set of tables, perhaps a book containing
// a number of tables, one per page.  The indices could be thought of as
// representing the pages, rows and columns (in that order).
// 4. A 4-dimensional array could then be thought of as a number of volumes
// of books, all of the same size, with an index specifying a volume, page,
// row and column.  As with 2-dimensional arrays, we need not specify all of
// the dimensions in a declaration of a higher-dimensional array.

No comments:

Post a Comment