explain the following terms declaring allocating


Explain the following terms declaring, Allocating and initializing two dimensional array?

Two dimensional arrays are declared, allocated and initialized much such as one dimensional arrays. Therefore you have to specify two dimensions rather than one, and you classically use two nested for loops to fill the array.

This example fills a two-dimensional array along with the sum of the row and column indexes

class FillArray {
   public static void main (String args[]) {
      int[][] matrix;
    matrix = new int[4][5];
      for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        matrix[row][col] = row+col;
      }
    }
      }
  }

Of course the algorithm you use to fill the array depends fully on the use to that the array is to be put. The further example calculates the identity matrix for a given dimension. The identity matrix of dimension N is a square matrix that contains ones along the diagonal and zeros in all other positions.

class IDMatrix {
   public static void main (String args[]) {
      double[][] id;
    id = new double[4][4];
      for (int row=0; row < 4; row++) {
      for (int col=0; col < 4; col++) {
        if (row != col) {
          id[row][col]=0.0;
        }
        else {
          id[row][col] = 1.0;
        }
      }
    }
      }
  }

In two-dimensional arrays ArrayIndexOutOfBoundsExceptions occur while you exceed the maximum column index or row index.

You can also allocate, declare, and initialize a a two-dimensional array at the similar time through providing a list of the initial values inside nested brackets. For example the three by three identity matrix could be set up like this:

double[][] ID3 = {
  {1.0, 0.0, 0.0},
  {0.0, 1.0, 0.0},
  {0.0, 0.0, 1.0}
};

The spacing and the line breaks used above are purely for the programmer. The compiler doesn't care. The subsequent works equally well:

double[][] ID3 = {{1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{0.0, 0.0, 1.0}};

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: explain the following terms declaring allocating
Reference No:- TGS0284445

Expected delivery within 24 Hours