Let’s learn pascal triangle in java using array.

## Pascal triangle in java using array

Here’s the algorithm to write pascal triangle using arrays we have to use two dimensional array. First declare integer variables num, a, b, arr[][], p.

Let user input value of variable ‘num’. Now set p = num – 1. In the next step set two dimensional array arr = new int[num][num].

Now using two for loops repeat for a = 0 to num (a < num) and for b = 0 to a(b <= a). In the next step using if else check if b == 0 or b == 1 then set arr[a][b] = 1, else set arr[a][b] = arr[a – 1][b – 1] + arr[a – 1][b]; display output.

Now repeat for loop for a = 0 to num (a < num), for b = 0 to p and leave blank space. Decrease value of variable p by 1.

Repeat for loop for b = 0 to a (b <= a). print blank space. Here’s program to display pascal triangle using array.

import java.util.Scanner; public class PascalTriangleUsingArray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num, a, b, arr[][], p; System.out.println("Please enter number of rows: "); num = sc.nextInt(); p = num - 1; arr = new int[num][num]; for(a = 0; a < num; a++) { for(b = 0; b <= a; b++) if(b == 0 || b == a) arr[a][b] = 1; else arr[a][b] = arr[a - 1][b - 1] + arr[a - 1][b]; } System.out.println("Pascal's triangle: \n"); for(a = 0; a < num; a++) { for(b = 0; b <= p; b++) System.out.print(" "); p--; for(b = 0; b <= a; b++) System.out.print(arr[a][b] + " "); System.out.println(); } sc.close(); } }

**Output:**

Please enter number of rows:

6

Pascal’s triangle:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Also read – major features of java