pascal's triangle java 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: how to find the ith row of pascal's triangle in c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N;
scanf("%d", &N);
int pascalArray[N + 1][N + 1];
int i, j;
if(0 <= N && N <= 20)
{
for (i = 0; i < N + 1; i++)
{
for(j = 0; j <= i; j++)
{
if(j == 0 || j == i)
pascalArray[i][j] = 1;
else
pascalArray[i][j] = pascalArray[i-1][j-1] + pascalArray[i-1][j];
if (i == N)
printf("%d ", pascalArray[i][j]);
}
}
}
return 0;
}
Example 3: 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();
}
}