Multidimensional Array

An multidimensional arrays are arrays of arrays. To declare a multidimensional array (2-D) variable, specify each additional index using another set of square brackets. For example,
int twoD[ ][ ]  =  new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int. You require two "for" loops to implement 2-D array.

PROGRAM
class TwoDArrayDemo {

 public static void main(String[] args) {
  
  int twoD[][]= new int[4][5];
  
  int i, j, k = 0;
  
  for(i=0; i<4; i++)
   for(j=0; j<5; j++) {
    twoD[i][j] = k;
    k++;
  }
  
  for(i=0; i<4; i++) {
   for(j=0; j<5; j++)
    System.out.print(twoD[i][j] + " ");
   System.out.println();
  }

 }
}
OUTPUT
C:\>javac TwoDArrayDemo.java
C:\>java TwoDArrayDemo
0 1 2 3 4 
5 6 7 8 9 
10 11 12 13 14 
15 16 17 18 19

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet