Wednesday, 17 December 2014

// The "MultiDimensionalArraysExample1" class.  Page 319.
// Example 1.  (from the Carter book)

// A table of int values with 3 rows and 6 columns can be created
// using the following declaration:

public class MultiDimensionalArraysExample1
{
    public static void main (String[] args)
    {
        // the first [] is the row, and the second [] is the column
        int[] [] table = new int [3] [6];
        // As we have seen, this really creates 3 arrays - each containing 6 elements
        // but, we can think of it as shown in the diagram on page 320 (top of page).
        // Just as for loop statements are used to index through a 1-dimensional array,
        // nested for loop statements are usually used to index through a
        // 2-dimensional array.  For the array called "table" in Example 1 here,
        // we can initialize all of the elements to 100 using the following code:
        for (int row = 0 ; row < table.length ; row++)
        {
            for (int col = 0 ; col < table [0].length ; col++)
            {
                table [row] [col] = 100;
            } // end of inner for loop # 1
        } // end of outer for loop # 1

        // Now, to view the element values of the "table" array,
        // we can clearly see the 3 rows and the 6 columns using this code:

        for (int row = 0 ; row < table.length ; row++)
        {
            System.out.println ();  // a return here makes a new row of values
            for (int col = 0 ; col < table [0].length ; col++)
            {
                // this makes the values print out on one line per row
                // with a space in between each value in each row
                System.out.print (table [row] [col] + " ");
            } // end of inner for loop # 2
        } // end of outer for loop # 2

        System.out.println ();

    } // main method
} // MultiDimensionalArraysExample1 class

No comments:

Post a Comment