I am trying to print pascal's triangle using 2D int array
And printing 2D array in below way
public static void pascal (int n)
{
int[][] pascalArray = new int[n][n];
// Code here
}
printArray(pascalArray);
public static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<array[i].length;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
For n =4
I am getting below output
Enter rows in the Pascal's triangle (or 0 to quit): 4
1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1
Now I want white-space instead of zero or an isosceles triangle format for pretty print
Is that possible in for 2D int array or can we change 2D int array into some string array in printArray method and achieve the same?
I tried system.out.format but some how I am unable to get the output because of int 2D array
If you know you want a triangle, and you know the array is square, you could simply change the upper bound of the inner loop.
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<=i; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}