Write a java program to print the Pascal’s Triangle using a 2-d array.
import java.util.Scanner;
public class App {
/** Main Method */
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter the no. of rows: ");
int n = keyBoard.nextInt();
int pascal[][] = new int[50][50];
int i = 0, j = 0, space = n - 1;
for (i = 0; i < n; i++) {
pascal[i][i] = pascal[i][0] = 1; // to assign value 1 to the diagonals
}
for (i = 0; i < n; i++) {
for (j = 1; j < i; j++) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < space; j++) // loop for printing the spaces
{
System.out.print(" ");
}
for (j = 0; j <= i; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
space--;
}
keyBoard.close();
}
}
Comments
Leave a comment