Credits

Saturday, February 28, 2009

Multi-Dimensional Arrays of Java

Typical in other programming languages are two - dimensional arrays. In Java, we can have more than 2-D arrays.

General syntax for 2-D array:

datatype arrayname[ ][ ] = new datatype[row_size][col_size];

eg.:
int table[ ] [ ] =new int[3][2];

Check the sample programs below:



[+/-] show/hide



class TwoDarray{
public static void main(String args[]){
int t, i;
int table [][]=new int[3][4];
for (t=0;t<3;t++){
for (i=0;i<4;++i){
table[t][i]=(t*4)+i+1;
System.out.print(table[t][i]+" ");
}
System.out.println();}}}

/* another program*/

class TwoDarray{
public static void main(String args[]){
int sqrs[][]={
{1,1},
{2,4},
{3,9}};

int i,j;
for (i=0;i<10;i++){
for (j=0;j<2;++j){
System.out.print(sqrs[i][j]+" ");
System.out.println();
}}}}

What are the output of these two classes?

AddThis