Wrong multidiemnsional-array initialization trying to build the pascal triangle (JAVA) -


i trying write class creates object of pascal triangle using multidimensional arrays. have in place (at least think so) except correct initialization of array. program reads follow:

class pascal{  //object variables int size; int[][] pascal;  pascal(int size){ //constructor      this.size = size; //defines how many rows/columns triangle has.     pascal = new int[size][];      //allocation of arrays      for(int i=0;i<pascal.length;i++)         pascal[i] = new int[i+1];      pascal[0][0] = 1; //the tip of triangle one. need value start with.       //initialisation of 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 first , last element of actual array x                  else                     pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//initialisation of elements in between              }         }     }  }   //the print method needed display 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 particiular example (new pascal(5);) should be:

    1    1 1   1 2 1  1 3 3 1 1 4 6 4 1 

and yet is:

    1    2 1   1 1 1  1 0 1 1 1 0 0 0 1 

i know problem must somewhere in array initialization part of code , it's simple mistake, starring @ monitor doesn't me anywhere anymore :/

just in case don't want give me answer: understanding array element pascal[1][0] should 1 instead of 2, because when for-loops value x 1 , value y 0 if-condition if( y==0 || y==pascal[x].length-1) should apply setting pascal[1][0] = 1.

thanks help!

in constructor, when initializing 2d array, in else, assignment incorrect. want initialize current element, left hand side incorrect (and inconsistent if):

pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1]; 

try [x][y] element itself.

pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1]; 

making change, correct output:

     1      1 1     1 2 1    1 3 3 1   1 4 6 4 1  

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -