Sunday, August 16, 2009

Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very interesting yet basic Java program, that displays the Pascal Triangle for any given integer value.

A Pascal Triangle is a triangle in which a triangle is formed of numbers, in which 1 is displayed one time, 2 is displayed two times, 3 is displayed three times, and so on, up to the entered value of the integer value. Each of these different numbers are displayed on different lines, but the same number is displayed on the same line. The whole structure is in the form of a triangle, and it is called Pascal Triangle.

The Java Code is provided below, the code asks the user to enter a number, and then prints the Pascal Triangle up to that many rows:-

 package developer;


 public class Pascal {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter the number of rows for which the Pascal Triangle is requird: ");
        InputStreamReader is = new InputStreamReader(;
        BufferedReader bf = new BufferedReader(is);
        int numRow = Integer.parseInt(bf.readLine());

        for (int i = 1; i <= numRow; i++) {
            // Prints the blank spaces
            for (int j = 1; j <= numRow - i; j++) {
                System.out.print(" ");
            // Prints the value of the number
            for (int k = 1; k <= i; k++) {
                System.out.print(i + " ");

I hope the above code was helpful to you all. For more information on Java, you know that Java Code Online is the place you need to be at.

Other Java Programs that might be of interest:-
Palindrome Program in Java
Factorial Program in Java
Fibonacci Series Program in Java
Prime Number Program in Java
String In Java

1 comment:

  1. This is wrong
    This is not the correct pascal triangle

    try this

    public static void main(String[] args) {
    int N = Integer.parseInt(args[0]);
    int[][] pascal = new int[N+1][];

    // initialize first row
    pascal[0] = new int[3];
    pascal[0][1] = 1;

    // fill in Pascal's triangle
    for (int i = 1; i <= N; i++) {
    pascal[i] = new int[i + 3];
    for (int j = 1; j < pascal[i].length - 1; j++)
    pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];

    // print results
    for (int i = 0; i <= N; i++) {
    for (int j = 1; j < pascal[i].length - 1; j++) {
    System.out.print(pascal[i][j] + " ");


Note: Only a member of this blog may post a comment.