1

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

  • 1
    You could just have a check in your loop that checks to see if it's zero, and if it is, print a space instead of a 0. – Evan LaHurd Sep 16 '15 at 21:07
  • @EvanLaHurd i tried if (array[i][j]==0) array[i][j]= ' '; But array is int 2D and it is unable to assign white space , I tried unicode also but still not showing the way I want. –  Sep 16 '15 at 21:10
  • Don't assign the space to `array[i][j]`, just use `System.out.print(" ");` – Evan LaHurd Sep 16 '15 at 21:14
  • Thanks for input .. but some how I am getting java.lang.ArrayIndexOutOfBoundsException for doing that!!! –  Sep 16 '15 at 21:20
  • Then you're doing something wrong...if you're only adding a check for 0 and printing a space instead of 0, then it shouldn't do that if it already wasn't. Either way, Andy's answer is your best bet! – Evan LaHurd Sep 16 '15 at 21:22

2 Answers2

2

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();
     } 
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Oh yes!!!! I didn't think that way... thanks for the info man... It seems I made a newbie mistake here. –  Sep 16 '15 at 21:16
0

You may just add the instruction that I added below. It prints only if the value in the array is not equal to "0". If it's a String array, use the equals() method

 for (int i = 0; i < array.length; i++)
 {
     for(int j=0; j<array[i].length;j++)
     {
         if (array[i][j] != 0) System.out.print(array[i][j] + " ");
     }
     System.out.println();
 } 
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89