# Q.9 Write a program to print the following as shown below - a) bell's triangle 1 1 2 2 3 5 5 7 10 15 15 20 27 37 52. what is wrong with this code?

//program to display bell’s triangle
class bell_triangle
{ public static void main(String args[])
{ int i,j,c=1;
int arr[][]=new int[];
for(i=0;i<5;i++)
{ arr[i]= new int[i+1];
}
arr=1;
for(i=1;i<5;i++)
{ for(j=0;j<i+1;j++)
{ if(j==0)
arr[i][j]=c;
else
arr[i][j]=arr[i-1][j-1]+arr[i][j-1];
// System.out.println(arr[i][j]);
}
c=arr[i][j];
}
for(i=0;i<5;i++)
for(j=0;j<i+1;j++)
{ System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}

The problem is when you reassign the last value of the previous row in c i.e. at line 20:
c = arr[i][j];
Since the loop above this line terminates when ‘j’ reaches i+1, which is out of bounds, what you try to access is actually arr[i][i+1], which doesn’t exist. For accessing the last element, change it to
c = arr[i][j-1];

Also while printing, the newline printing will be in the outer loop.

``````for(i=0;i<5;i++) {
for(j=0;j<i+1;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
``````

Rest of the code is fine.