pascal triangle geeks code example
Example 1: 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 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();
}
}