java pascal triangle program code example
Example 1: Java program to display pascal triangle
import java.util.Scanner;
public class PascalsTriangleJava
{
static int findFactorial(int number)
{
int factorial;
for(factorial = 1; number > 1; number--)
{
factorial *= number;
}
return factorial;
}
static int printPascalTraingle(int num, int p)
{
return findFactorial(num) / (findFactorial(num - p) * findFactorial(p));
}
public static void main(String[] args)
{
int row, a, b;
System.out.println("Please enter number of rows: ");
Scanner sc = new Scanner(System.in);
row = sc.nextInt();
System.out.println("Here's is pascal's triangle: ");
for(a = 0; a < row; a++)
{
for(b = 0; b < row - a; b++)
{
System.out.print(" ");
}
for(b = 0; b <= a; b++)
{
System.out.print(" " + printPascalTraingle(a, b));
}
System.out.println();
}
sc.close();
}
}
Example 2: pascals triangle java
import java.util.*;
public class PascalTriangleCreator
{
public static long factorial(long n){
long factorial;
if (n==0){
factorial=1;
}
else{
factorial=1;
for (int counter=1;counter<=n;counter++){
factorial=factorial*counter;
}
}
return factorial;
}
public static long FinalValue(long n, long r){
return factorial(n) / ( factorial(n-r) * factorial(r) );
}
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
long rows=1;
long i,j;
while (rows!=0){
System.out.println("How many rows of Pascal's triangle would you like to print? (0 to stop; 1-20 rows)");
rows=sc.nextLong();
while (rows<0||rows>20){
System.out.println("Invalid input.");
System.out.println("How many rows of Pascal's triangle would you like to print? (0 to stop; 1-20 rows)");
rows=sc.nextLong();
}
if (rows==0){
System.out.println("Program terminated by user.");
}
else{
for(i = 0; i < rows; i++) {
for(j = 0; j <= rows-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
if ((FinalValue(i, j))>9999) {
System.out.print(" ");
}
else if ((FinalValue(i, j))>999){
System.out.print(" ");
}
else if ((FinalValue(i, j))>99){
System.out.print(" ");
}
else if ((FinalValue(i, j))>9){
System.out.print(" ");
}
else{
System.out.print(" ");
}
System.out.print(FinalValue(i, j));
}
System.out.println();
}
}
}
sc.close();
}
}