Q:

Java program to print Pascal\'s triangle

belongs to collection: Java Basic Programs

0

Example:

Input:
Enter number of rows: 10

Output:
Pascal's Triangle :
                                              1
                                           1      1
                                        1      2      1
                                     1      3      3      1
                                  1      4      6      4      1
                               1      5      10      10      5      1
                            1      6      15      20      15      6      1
                         1      7      21      35      35      21      7      1
                      1      8      28      56      70      56      28      8      1
                   1      9      36      84      126      126      84      36      9  

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print Pascal's triangle in java

import java.util.Scanner;

public class Pattern13
{
	public static void main(String[] args) 
	{
		// initialize variables.
		int lib,p,q,r,x;

		// create object of scanner.
		Scanner s=new Scanner(System.in);

		// enter number of rows.
		System.out.print("Enter the rows : ");
		r=s.nextInt();
		lib=1;  
		q=0;

		// here the pascals triangle.
		System.out.println("Pascal's Triangle : ");

		while(q<r)
		{
			for(p=40-3*q;p>0;--p)
			System.out.print(" ");
			for(x=0;x<=q;++x)
			{
				if((x==0)||(q==0))
					lib=1;
				else
					lib=(lib*(q-x+1))/x;
				System.out.print("      ");
				System.out.print(lib);
			}
			System.out.println("");
			++q;
		}
	}
}

Output

Enter the rows : 10
Pascal's Triangle :
                                              1
                                           1      1
                                        1      2      1
                                     1      3      3      1
                                  1      4      6      4      1
                               1      5      10      10      5      1
                            1      6      15      20      15      6      1
                         1      7      21      35      35      21      7      1
                      1      8      28      56      70      56      28      8      1
                   1      9      36      84      126      126      84      36      9  

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to generate permutation and combinati... >>
<< Java program to print pattern of alphabets...