Sunday, January 15, 2012

Arrays


1. Two Dimentional Array Example

class ArrayDemo
{
public static void main(String args[])
{
int[]num={1,2,3,4,5}; //Single Dimensional Array
System.out.println("Array Length:" + num.length);

int k=0;
int [][] twoD=new int[4][5]; //Two Dimensional array (even columns)
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
twoD[i][j]=k;    //Storing 1 to 19 in two dimentional array
k++;
}

}

for(int i=0;i<4;i++)      //Displaying the elements from two dimentional array
{
for(int j=0;j<5;j++)
{
System.out.print(twoD[i][j]+"   ");
}
System.out.println();

}

}
}

Output:

Array Length:5
0   1   2   3   4
5   6   7   8   9
10   11   12   13   14
15   16   17   18   19

2. Two Dimensional (Uneven column) Array Example

public class Uneven
{
public static void main(String args[])
{
int [][] twoD=new int[4][];      //Two dimensional with Uneven columns array declaration
int k=0;
twoD[0]=new int[1];
twoD[1]=new int[2];
twoD[2]=new int[3];
twoD[3]=new int[4];
for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
twoD[i][j]=k;
k++;
}
}

for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
System.out.print(twoD[i][j]+" ");
}
System.out.println();
}
}
}

Output:

0
1 2
3 4 5
6 7 8 9


No comments:

Post a Comment