Answer to Question #309537 in Java | JSP | JSF for Kyle

Question #309537

Write a java program to print the Pascal’s Triangle using a 2-d array.


1
Expert's answer
2022-03-20T06:21:20-0400
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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS