Write a program to display Pascal’s Triangle in Java


//To display a Pascal’s Triangle

 

import java.util.Scanner;
public class Pascaltriangle

{
public static void main(String[] args)

{

Scanner scanner = new Scanner(System.in);
System.out.print(“Enter no of rows in Pascal’s triangle : “);
int rows = scanner.nextInt();
int nextNumber;
System.out.println(” “);

for (int a = 0; a < rows; a++) {
nextNumber = 1;

for(int b=0; b<(rows-a)*2; b++)  //create (rows-i)*2  spaces, for initial spacing.
System.out.print(” “);

for (int c = 0; c <= a; c++) {
System.out.format(“%5d”, nextNumber); // %4d creates 5 space between number.
nextNumber = nextNumber * (a – c) / (c + 1);
}
System.out.println();
}}}

output :

pascal

Related Posts

Comments are closed.