//program to display bell’s triangle
class bell_triangle
{ public static void main(String args[])
{ int i,j,c=1;
int arr[][]=new int[5][];
for(i=0;i<5;i++)
{ arr[i]= new int[i+1];
}
arr[0][0]=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.
Please format your question in civilized way. I hope someone will answer it then.