pascal triangle using array code example
Example 1: Pascal triangle in java 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();
}
}
Example 2: Pascal triangle program in java without using arrays
import java.util.Scanner;
public class PascalTriangleDemo
{
public static void main(String[] args)
{
System.out.println("Please enter number of rows to print pascal's triangle: ");
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
System.out.println("Pascal's triangle with " + row + " rows.");
displayPascalTriangle(row);
sc.close();
}
public static void displayPascalTriangle(int r)
{
for(int a = 0; a < r; a++)
{
int num = 1;
System.out.printf("%" + (r - a) * 2 + "s", "");
for(int b = 0; b <= a; b++)
{
System.out.printf("%4d", num);
num = num * (a - b) / (b + 1);
}
System.out.println();
}
}
}