Friday, January 6, 2012

Generate Pascal Triangle in Java - Java Code for Pascal Triangle

It is a basic program to generate pascal triangle in Java language.

Pascal Triangle
It is a triangular array of the binomial coefficients in a triangle. Named Pascal comes from French mathematician, Blaise Pascal. In the program user input number. It generate rows for input number. In first row there is only the number 1. From all next rows, add the number directly above and to the left with the number directly above and to the right to find the new value.

Program Code
//Java Program to print Pascal Triangle
import java.util.*;
class Pascal 
 public static void main(String[] args) 
    System.out.print("Enter no of rows for pascal triangle: ");
    Scanner console=new Scanner(;
    int num=console.nextInt();
    for (int i = 0; i < num; i++)
                        int c = 1;
                        for(int j = 0;j < num-i; j++)
                              System.out.print("   "); //blank space
                        for(int k = 0; k <= i; k++)
                              System.out.print("   ");
                              System.out.print(c); //print c value 
                              System.out.print(" ");
                              c = c * (i - k) / (k + 1);

Save Program at your system by name "".

Enter value for number of rows you want in pascal triangle


Hope, you like this post. :)

1 comment:

Post a Comment