Wednesday, 17 December 2014

// The "MultiDimensionalArraysExample3" class.  Page 321.
// Example 3.  (from the Carter book)

// The following program fragment creates a triangular
// array of double values (0.0) with one element in the first
// row, two elements in the second row, and so on, for
// a total of five rows:

public class MultiDimensionalArraysExample3
{
    public static void main (String[] args)
    {
        // note the absence of a column dimension in this
        // declaration but, the row dimension is legally required
        double[] [] triTable = new double [5] [];
        // configure this triangular array with the following code:

        for (int row = 0 ; row < triTable.length ; row++)
        {
            // you only need to refer to the row dimension here,
            // since there is no column dimension specified -->
            // (add one to each row of this array):

            triTable [row] = new double [row + 1];
        } // end of for loop

        // we can picture the resulting triangular shape of
        // the "triTable" array, as follows:

        for (int row = 0 ; row < triTable.length ; row++)
        {
            System.out.println (); // force a return at the end of each row
            // a virtual "col" may usually vary at the same rate as "row"
            for (int col = 0 ; col <= row ; col++)
            {
                System.out.print (triTable [row] [col] + " ");
            } // end of inner for loop
        } // end of outer for loop

        System.out.println ();

    } // main method
} // MultiDimensionalArraysExample3 class

No comments:

Post a Comment