java program to print pascal triangle 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;
   }
   // here's the function to display pascal's triangle
   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: 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;
}