by Dinesh Thakur

Like one dimensional array, one can also initialize multidimensional array when they are declared. For example: A two-dimensional array table with 2 rows and 3 columns can be declared and initialized as follows,

int table[] [] = {{1,2,3},{3,4,5}};

Note that each array row is initialized separately by enclosing them within its own set of curly braces. Moreover, there must be a comma at the end of each row except for the last one. Within each row, the first value will be stored in the first position of the sub array, the second value will be stored in the second position and so on.

Now let us consider a program to calculate sum of elements of each row in two dimensional array.

public class SumRC
{
      public static void main(String [] args)
    {
           int[] [] num = {{7,6,5},{4,5,3}};
           int i,j,sumRow,sumCol;
           for( i=0; i<num.length; i++)
               {
                   sumRow = 0;
                   for (j=0; j<num[i].length;j++)
                        {
                               sumRow += num[i][j];
                               System.out.print( num[i] [j] + "  ");
                        }
                               System.out.println("---  " + sumRow);
          
                }
                  System.out.println("-------------------------- ");
                  for(i=0; i<num[0].length; i++)
                      {
                          sumCol = 0;
                          for( j=0; j<num.length; j++)
                              sumCol += num[j] [i];
                              System.out.print(sumCol + "  ");
                      }
      }
}

Initialization of Two Dimensional Arrays Java