I am trying to write a class that creates an object of a pascal triangle using multidimensional arrays. Now i do have everything in place (at least i think so) except for the correct Initialization of the array. My program reads as follow:
class Pascal{
//Object variables
int size;
int[][] pascal;
Pascal(int size){ //Constructor
this.size = size; //Defines how many rows/columns the triangle has.
pascal = new int[size][];
//Allocation of the arrays
for(int i=0;i<pascal.length;i++)
pascal[i] = new int[i+1];
pascal[0][0] = 1; //the tip of the triangle is always one. Also you need a value to start with.
//Initialisation of the elements
for(int x=0;x<pascal.length;x++){
for(int y=0;y<pascal[x].length;y++){
if(x>0){
if(y==0 || y == (pascal[x].length)-1)
pascal[x][y] = 1; //Initialisation of the first and last element of the actual array x
else
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//Initialisation of all elements in between
}
}
}
}
//The print method needed to display the pascal triangle
void print(){
for(int i=0;i<pascal.length;i++){
for(int k=pascal.length;k>i;k--)
System.out.print(" ");
for(int j=0;j<pascal[i].length;j++)
System.out.print(pascal[i][j]+" ");
System.out.println();
}
}
//main function
public static void main(String... args){
Pascal p = new Pascal(5); //example triangle consisting of 5 rows total
p.print();
}
}
The output in this particiular example (new Pascal(5);) should be:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
And yet it is:
1
2 1
1 1 1
1 0 1 1
1 0 0 0 1
I know the problem must be somewhere in the array initialization part of the code and it's probably a simple mistake, but starring at the monitor doesn't get me anywhere anymore :/
Just in case you don't just want to give me the answer: From my understanding the array element pascal[1][0] should be 1 instead of 2, because when the for-loops value x is 1 and value y is 0 the if-condition if( y==0 || y==pascal[x].length-1) should apply thus setting pascal[1][0] = 1.
Thanks for your help!
In the constructor, when initializing the 2D array, in the else
, your assignment is incorrect. You want to initialize the current element, but the left hand side is incorrect (and inconsistent with the if
):
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];
Try the [x][y]
element itself.
pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1];
Making only this change, I get the correct output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1