pascal triangle program in java without using arrays

Solutions on MaxInterview for pascal triangle program in java without using arrays by the best coders in the world

showing results for - "pascal triangle program in java without using arrays"
Antonia
11 Jan 2020
1// Pascal triangle in java using array
2import java.util.Scanner;
3public class PascalTriangleUsingArray
4{
5   public static void main(String[] args)
6   {
7      Scanner sc = new Scanner(System.in);
8      int num, a, b, arr[][], p;
9      System.out.println("Please enter number of rows: ");
10      num = sc.nextInt();
11      p = num - 1;
12      arr = new int[num][num];
13      for(a = 0; a < num; a++)
14      {
15         for(b = 0; b <= a; b++)
16            if(b == 0 || b == a)
17               arr[a][b] = 1;
18            else
19               arr[a][b] = arr[a - 1][b - 1] + arr[a - 1][b];
20      }
21      System.out.println("Pascal's triangle: \n");
22      for(a = 0; a < num; a++)
23      {
24         for(b = 0; b <= p; b++)
25            System.out.print(" ");
26         p--;
27         for(b = 0; b <= a; b++)
28            System.out.print(arr[a][b] + " ");
29         System.out.println();
30      }
31      sc.close();
32   }
33}
Jean
05 Jan 2017
1// Pascal triangle program in java without using arrays
2import java.util.Scanner;
3public class PascalTriangleDemo 
4{
5   public static void main(String[] args) 
6   {
7      System.out.println("Please enter number of rows to print pascal's triangle: ");
8      Scanner sc = new Scanner(System.in);
9      int row = sc.nextInt();            
10      System.out.println("Pascal's triangle with " + row + " rows.");
11      displayPascalTriangle(row);
12      sc.close();
13   }
14   public static void displayPascalTriangle(int r) 
15   {
16      for(int a = 0; a < r; a++) 
17      {
18         int num = 1;
19         System.out.printf("%" + (r - a) * 2 + "s", "");
20         for(int b = 0; b <= a; b++) 
21         {
22            System.out.printf("%4d", num);
23            num = num * (a - b) / (b + 1);
24         }
25         System.out.println();
26      }
27   }
28}