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
Category: Java Programming Number Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments