pascal triangle code code example
Example 1: program to print pascal triangle
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
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();
}
}