Docstoc

Multi-Dimensional Arrays

Document Sample
Multi-Dimensional Arrays Powered By Docstoc
					                                 Multi-Dimensional Arrays
In previous lectures we have been focusing on one-dimensional arrays, which can be used to
represent lists of related values. In addition to one-dimensional arrays we can create arrays with two,
three, or even more dimensions. These are called multi-dimensional arrays.


Two-dimensional arrays

Two dimensional arrays (2-D array) are used to store data that is best represented as a “table” of
values. A 2-D array is a collection of a fixed number of elements arranged in rows and columns,
where all the elements are of the same data type. We can envision a 2 X 3 array as a “table” with two
rows and 3 columns.




Declaring 2-D arrays

The syntax for declaring 2-D arrays is similar to that for one dimensional arrays

      type[][] arrayName;
             or
      type[][] arrayName = new type[N][M];


Where:
  o “type” represents the data type of each element in the array.
  o Each dimension is specified by a set of braces: []
  o N & M are integer expressions, literals, or variables which indicate how many rows and
     columns to allocate… The first dimension represents “rows” and the second “columns”

To declare an integer array with 3 rows and 2 columns

int [][] newArray = new int [3] [2];

Hint: remember, array elements are initialized java so that numeric elements are zero, characters
are „ „, and elements of an object type are set to NULL.
Initializing array components

2-D arrays can be initialized during declaration using the following syntax:

int [][] newArray = {{row1 values}, {row 2 values},….., {row N values}};


Each value must be separated by a comma, and the values for each row must be contained within a
set of braces {}. For example, to allocate and initialize a 3 X 2 array of integers:


int [][] newArray = { { 2, 3} , { 5, 8} , {9, 1}};

Which allocates an arrays in the form:


                                           2                   3

                                           5                   8

                                           9                   1




Access individual array elements

As with one-dimensional arrays, each element in a multi-dimensional array has an index value. The
range of index values for each row begins at 0 and goes up to # of rows - 1. The range of index
values for each column begins at 0 and goes up to # of columns -1. For example, if we have the
following declaration of an array with 10 rows and 5 columns:

int[][] newArray = new int[10][5];

The index values would be:
                              [0]         [1]         [2]         [3]         [4]

                  [0]

                  [1]                    [1][1]

                  [2]

                  [3]

                  [4]                                [4][2]      [4][3]

                  [5]        [5][0]

                  [6]

                  [7]

                  [8]

                  [9]                                                        [9][4]



The index of an individual element, is determined by intersecting its row and column number. The
value of array elements can be retrieved or set using their index number.

newArray[3][2] = 99;

                              [0]         [1]         [2]         [3]         [4]

                  [0]

                  [1]

                  [2]

                  [3]                                 99
                  [4]

                  [5]

                  [6]

                  [7]

                  [8]

                  [9]
The “length” instance property can also be applied to multi-dimensional arrays.

int [][] newArray = new int [3][2];

newArray.length will return the value 3, because each row in the array is a one-dimensional array,
and newArray[0] refers to the first row. To determine the number of entries in each column we
would specify:

newArray[0].length which would return 2.


Processing 2-D arrays

A 2-D array can be processed in 3 ways:

         o Process the entire array
         o Process a particular row of the array, called row processing
         o Process a particular column of the array, called column processing

Initialization and printing:
Example 1: Create a 4 X 5 integer array, initialize all elements in the first row to 1, the second
row to 2, and so forth.

public class ex1 {
 public static void main(String args[]) {                          The output of this program
                                                                   is:
         int[][] array1 = new int[4][5];
         int initValue=1;
                                                                   11111
         // Initialize each array element                          22222
                                                                   33333
         for (int i=0; i < array1.length; i++) {                   44444
                  for (int j=0; j < array1[0].length; j++)
                           array1[i][j] = initValue;

                 initValue++;
         }

         // Print out the array
         for (int i=0; i < array1.length; i++) {
                  for (int j=0; j < array1[0].length; j++)
                           System.out.print(array1[i][j] + " ");

                 System.out.println();
         }

    } // end of main
}
Passing a 2-D Array to a method:
We can create a generalization of the previous method, by moving the part of the code that performs
initialization and printing to static methods, which then can be called from the body of main.

public class ex2a {
 public static void main(String args[]) {

         int[][] array1 = new int[4][5];
         int value=99;

         initialize(array1, array1.length, array1[0].length, value);

         print(array1, array1.length, array1[0].length);



    } // end of main

    public static void initialize( int [][] array, int numRows, int numColumns, int

initValue) {

         // Initialize each array element

         for (int i=0; i < numRows; i++) {
                  for (int j=0; j < numColumns; j++)
                           array[i][j] = initValue;

          }
    }// end initialize

     public static void print( int[][] array, int numRows, int numColumns) {

         // Print out the array
                                                                  This program prints:
         for (int i=0; i < numRows; i++) {
                  for (int j=0; j < numColumns; j++)
                                                                  99 99 99 99 99
                           System.out.print(array[i][j] + " ");
                                                                  99 99 99 99 99
                                                                  99 99 99 99 99
                 System.out.println();
                                                                  99 99 99 99 99
         }

     }// end print

}
Initialization with keyboard input:
    In this example, the array will be initialized with values received via keyboard input.

import java.util.*;

public class ex3 {
 public static void main(String args[]) {

           int[][] array1 = new int[4][5];
           int value=99;                                                           Please enter a value for element[0][0]
                                                                                   10
           initialize(array1, array1.length, array1[0].length);                    Please enter a value for element[0][1]
                                                                                   3
           print(array1, array1.length, array1[0].length);                         Please enter a value for element[0][2]
                                                                                   1
                                                                                   Please enter a value for element[0][3]
                                                                                   4
    } // end of main                                                               Please enter a value for element[0][4]
                                                                                   6
    public static void initialize( int [][] array, int numRows, int numColumns){   Please enter a value for element[1][0]
                                                                                   9
           Scanner in = new Scanner(System.in);                                    Please enter a value for element[1][1]
                                                                                   3
                                                                                   Please enter a value for element[1][2]
           // Initialize each array element                                        4
                                                                                   Please enter a value for element[1][3]
           for (int i=0; i < numRows; i++) {                                       5
                     for (int j=0; j < numColumns; j++) {                          Please enter a value for element[1][4]
                     System.out.println("Please enter a value for element["        6
                               + i + "][" + j + "]");                              Please enter a value for element[2][0]
                                                                                   6
                             array[i][j] = in.nextInt();                           Please enter a value for element[2][1]
                                                                                   3
                    }// end of inner for                                           Please enter a value for element[2][2]
           }// end of outer for                                                    4
                                                                                   Please enter a value for element[2][3]
    }// end initialize                                                             1
                                                                                   Please enter a value for element[2][4]
     public static void print( int[][] array, int numRows, int numColumns) {       5
                                                                                   Please enter a value for element[3][0]
           // Print out the array                                                  7
           for (int i=0; i < numRows; i++) {                                       Please enter a value for element[3][1]
                     for (int j=0; j < numColumns; j++)                            9
                               System.out.print(array[i][j] + " ");                Please enter a value for element[3][2]
                                                                                   0
                     System.out.println();                                         Please enter a value for element[3][3]
           }                                                                       1
                                                                                   Please enter a value for element[3][4]
     }// end print                                                                 2
                                                                                   10 3 1 4 6
}                                                                                  93456
                                                                                   63415
                                                                                   79012
Initializing from a file:
import java.util.*;
import java.io.*;

public class ex4 {
 public static void main(String args[]) throws IOException {

         int[][] array1 = new int[4][5];
         int value=99;

         initialize(array1, array1.length, array1[0].length);

         print(array1, array1.length, array1[0].length);

    } // end of main

    public static void initialize( int [][] array, int numRows, int numColumns) throws IOException{

         // Initialize each array element

         FileReader infile = new FileReader("ex4.dat");                 This displays
         Scanner in = new Scanner(infile);

          for (int i=0; i < numRows && in.hasNextLine(); i++) {         01234
                  for (int j=0; j < numColumns; j++) {                  10 11 12 13 14
                           array[i][j] = in.nextInt();                  20 21 22 23 24
                                                                        30 31 32 33 34
                   }// end of inner for
           }// end of outer for
       }// end try
    }// end initialize

     public static void print( int[][] array, int numRows, int numColumns) {

         // Print out the array
         for (int i=0; i < numRows; i++) {
                  for (int j=0; j < numColumns; j++)
                           System.out.print(array[i][j] + " ");

                 System.out.println();
          }
     }// end print

}
Sum by row
In this example, we will initialize our array via keyboard input, print it out, and then calculate and
display the sum of the values in each row.
import java.util.*;

public class ex5 {
 public static void main(String args[]) {

       final int ROWS = 4;
       final int COLUMNS = 5;
       int[][] array1 = new int[ROWS][COLUMNS];
       int[] sumOfRows = new int[ROWS];
       int value=99;

       initialize(array1, ROWS, COLUMNS);

       print(array1, ROWS, COLUMNS);

       sumRows(sumOfRows, array1, ROWS, COLUMNS);

       for (int i=0; i < ROWS; i++){
         System.out.print("The elements in row " + i + " are ");

           for(int j=0; j < COLUMNS; j++)
                System.out.print(array1[i][j] + " ");

           System.out.println(" The sum of the elements is: " + sumOfRows[i]);
       }

 } // end of main

  public static void initialize( int [][] array, int numRows, int numColumns){

       Scanner in = new Scanner(System.in);


       // Initialize each array element

       for (int i=0; i < numRows; i++) {
               for (int j=0; j < numColumns; j++) {
                       System.out.println("Please enter a value for element["
                       + i + "][" + j + "]");

                       array[i][j] = in.nextInt();

              }// end of inner for
       }// end of outer for

  }// end initialize
public static void print( int[][] array, int numRows, int numColumns) {

        // Print out the array
        for (int i=0; i < numRows; i++) {
                for (int j=0; j < numColumns; j++)
                        System.out.print(array[i][j] + " ");

               System.out.println();
        }

    }// end print

    public static void sumRows( int[] sums, int[][] array, int rows, int columns){

        // initialize the sums array
          Arrays.fill(sums, 0);


        // Sum the values in each row, and store the result in the corresponding
        // element of array sums.

        for (int i=0; i < rows; i++ )
                for (int j=0; j < columns; j++)
                        sums[i] = sums[i] + array[i][j];

    }// end sumRows

}
Please enter a value for element[0][0]
5
Please enter a value for element[0][1]
4
Please enter a value for element[0][2]
8
Please enter a value for element[0][3]
2
Please enter a value for element[0][4]
4
Please enter a value for element[1][0]
9
Please enter a value for element[1][1]
5
Please enter a value for element[1][2]
6
Please enter a value for element[1][3]
7
Please enter a value for element[1][4]
2
Please enter a value for element[2][0]
1
Please enter a value for element[2][1]
9
Please enter a value for element[2][2]
3
Please enter a value for element[2][3]
6
Please enter a value for element[2][4]
2
Please enter a value for element[3][0]
8
Please enter a value for element[3][1]
1
Please enter a value for element[3][2]
3
Please enter a value for element[3][3]
7
Please enter a value for element[3][4]
2

54824
95672
19362
81372

The elements in row 0 are 5 4 8 2 4   The sum of the elements is: 23
The elements in row 1 are 9 5 6 7 2   The sum of the elements is: 29
The elements in row 2 are 1 9 3 6 2   The sum of the elements is: 21
The elements in row 3 are 8 1 3 7 2   The sum of the elements is: 21
Finding the largest value in Each column
This example finds an prints the largest value stored in each column.

import java.util.*;

public class ex6 {
 public static void main(String args[]) {

       final int ROWS = 4;
       final int COLUMNS = 5;
       int[][] array1 = new int[ROWS][COLUMNS];
       int[] largestInColumns = new int[COLUMNS];
       int value=99;

       initialize(array1, ROWS, COLUMNS);

       print(array1, ROWS, COLUMNS);

       findLargestValue(largestInColumns, array1, ROWS, COLUMNS);

       for (int j=0; j < COLUMNS; j++){
         System.out.print("The elements in column " + j + " are ");

           for(int i=0; i < ROWS; i++)
                System.out.print(array1[i][j] + " ");

           System.out.println(" The largest value in column 1 is: " +
               largestInColumns[j]);
       }

 } // end of main

 public static void initialize( int [][] array, int numRows, int numColumns){

       Scanner in = new Scanner(System.in);


       // Initialize each array element

       for (int i=0; i < numRows; i++) {
               for (int j=0; j < numColumns; j++) {
                       System.out.println("Please enter a value for element["
                       + i + "][" + j + "]");

                      array[i][j] = in.nextInt();

              }// end of inner for
       }// end of outer for

 }// end initialize
public static void print( int[][] array, int numRows, int numColumns) {

        // Print out the array
        for (int i=0; i < numRows; i++) {
                for (int j=0; j < numColumns; j++)
                        System.out.print(array[i][j] + " ");

                 System.out.println();
        }

    }// end print

    public static void findLargestValue( int[] maxs, int[][] array, int rows,
                      int columns){

                 int max;


        //find the largest value in each column
        // we will loop through all of the values in each column

        for (int j=0; j < columns; j++) {
           max = array[0][j];

            for (int i=0; i < rows; i++ ){
                  if (max < array[i][j]) max = array[i][j];
        }

            // store the value in to the corresponding element of maxs

             maxs[j] = max;

        }// end outer for

    }// end findLargest

}
Please enter a value for element[0][0]
4
Please enter a value for element[0][1]
5
Please enter a value for element[0][2]
6
Please enter a value for element[0][3]
4
Please enter a value for element[0][4]
7
Please enter a value for element[1][0]
4
Please enter a value for element[1][1]
3
Please enter a value for element[1][2]
6
Please enter a value for element[1][3]
2
Please enter a value for element[1][4]
4
Please enter a value for element[2][0]

6
Please enter a value for element[2][1]
7
Please enter a value for element[2][2]
6
Please enter a value for element[2][3]
5
Please enter a value for element[2][4]
7
Please enter a value for element[3][0]
3
Please enter a value for element[3][1]
2
Please enter a value for element[3][2]
4
Please enter a value for element[3][3]
3
Please enter a value for element[3][4]
5
45647
43624
67657
32435
The elements in column 0 are 4 4 6 3     The largest value in column 1 is: 6
The elements in column 1 are 5 3 7 2     The largest value in column 1 is: 7
The elements in column 2 are 6 6 6 4     The largest value in column 1 is: 6
The elements in column 3 are 4 2 5 3     The largest value in column 1 is: 5
The elements in column 4 are 7 4 7 5     The largest value in column 1 is: 7
Reversing the elements on a diagonal.
This example reverses the elements along each diagonal in an array, where the number of rows and
columns are the same. (it is a square array)

import java.util.*;

public class ex7 {
 public static void main(String args[]) {

       final int ELEMENTS = 3;

       int[][] array1 = new int[ELEMENTS][ELEMENTS];

       initialize(array1, ELEMENTS, ELEMENTS);

       System.out.println("The original array is :");

       print(array1, ELEMENTS, ELEMENTS);

       reverse(array1, ELEMENTS, ELEMENTS);

       System.out.println("After reverse the array is: ");
       print(array1, ELEMENTS, ELEMENTS);

 } // end of main

 public static void initialize( int [][] array, int numRows, int numColumns){

       Scanner in = new Scanner(System.in);

       // Initialize each array element

       for (int i=0; i < numRows; i++) {
               for (int j=0; j < numColumns; j++) {
                        System.out.println("Please enter a value for element["
                        + i + "][" + j + "]");

                      array[i][j] = in.nextInt();

               }// end of inner for
       }// end of outer for

 }// end initialize

  public static void print( int[][] array, int numRows, int numColumns) {

       // Print out the array
       for (int i=0; i < numRows; i++) {
                for (int j=0; j < numColumns; j++)
                        System.out.print(array[i][j] + " ");

               System.out.println();
       }

  }// end print
    public static void reverse(int[][] array, int rows, int columns) {

          int temp, i, j;

          for ( i=0, j=rows-1; i <= (rows/2); i++, j--){
                  temp = array[i][i];
                  array[i][i] = array[j][j];
                  array[j][j] = temp;

                  temp = array[j][i];
                  array[j][i] = array[i][j];
                  array[i][j] = temp;
      }

    } // end reverse

}


           Please enter a value for element[0][0]
           1
           Please enter a value for element[0][1]
           2
           Please enter a value for element[0][2]
           3
           Please enter a value for element[1][0]
           5
           Please enter a value for element[1][1]
           6
           Please enter a value for element[1][2]
           7
           Please enter a value for element[2][0]
           9
           Please enter a value for element[2][1]
           8
           Please enter a value for element[2][2]
           5
           The original array is :
           123
           567
           985
           After reverse the array is:
           529
           567
           381

				
DOCUMENT INFO