Write a Java Program to Print Pascal Triangle using For Loop

By | 29.01.2017

Write a Java Program to Print Pascal Triangle using For Loop


To print pascal’s triangle in Java Programming, you have to use three for loops and start printing pascal’s triangle as shown in the following example.

java-pascal-triangle

Following Java Program ask to the user to enter the number of line/row upto which the Pascal’s triangle will be printed to print the Pascal’s triangle on the screen:

 

SOURCE CODE ::

 

import java.io.*;
public class Pascal
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter the number of rows : ");
        int r = Integer.parseInt(br.readLine());
        for(int i=0;i<r;i++)
        {
            for(int k=r;k>i;k--)
            {
                System.out.print(" ");
            }
            int number = 1;
            for(int j=0;j<=i;j++)
            {
 
                 System.out.print(number+" ");
                 number = number * (i - j) / (j + 1);
                  
            }
            System.out.println();
        }
 
    }
}

 

OUTPUT ::

 

Enter the number of rows : 6
      1 
     1 1 
    1 2 1 
   1 3 3 1 
  1 4 6 4 1 
 1 5 10 10 5 1

 

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments