We know that Java arrays are dynamic and 2 d array can be constructed with different number of columns. In this program we will create the 2 d array with 5 rows aned afterwards for the 1st row number of columns will be 1, for the second rwo number of columns will be 3 and so on.
While creating the number of columns for each row of the 2 d array, the ist column and the last column of each row will be filled up with 1.
Next job is to fill up the vacant columns of rows starting from number 2 with previous rows values. And the sequence is like arr[i][j]=arr[i-1][j-1] + arr[i-1][j], arr[i][j+1]=arr[i-1][j] + arr[i-1][j+1]and so on. After filling up the 2 d array, display the 2 d array.
class Pascal
{
int arr[][]=new int[5][];
int i,j,k;
Pascal()
{
arr[0]=new int [1];
arr[0][0]=1;
arr[1]=new int [2];
arr[1][0]=1;
arr[1][1]=1;
arr[2]=new int [3];
arr[2][0]=1;
arr[2][2]=1;
arr[3]=new int [4];
arr[3][0]=1;
arr[3][3]=1;
arr[4]=new int [5];
arr[4][0]=1;
arr[4][4]=1;
}
void show()
{
for(i=0;i< 5;i++)
{
for(k=i;k< 5;k++)
{
System.out.print(" ");
}
for(j=0;j< =i;j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
}
void set()
{
for(i=2;i< 5;i++)
{
for(j=1;j< i;j++)
{
arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
}
}
}
public static void main(String agrs[])
{
Pascal ob=new Pascal();
System.out.println(" Traingle with values at start and end of row only\n");
ob.show();
ob.set();
System.out.println(" Final array\n");
ob.show();
}
}
No comments:
Post a Comment