Home > Java > Java Program to print Pascal Triangle – Q13

Java Program to print Pascal Triangle – Q13


Q13: Java Program to print Pascal Triangle

import javax.swing.*;

class pascal{
	public static void main(String args[]){
		int lim, n, r, item, l;
		double x;
		String inp;
		
		inp = JOptionPane.showInputDialog("Enter Limit: ");
		lim = Integer.parseInt(inp);
		
		// For 1st Line
		for(l=0; l<=lim; l++)
			System.out.print("  ");
		System.out.println(" 1");
		
		//For rest Lines
		for(n=2; n<=lim; n++){
			for(l=n; l<=lim; l++){	// Loop for blank Pyramid
				System.out.print("  ");
			}
			for(r=0; r<=n; r++){	// Loop for Pascal Triangle
				x = fact(n)/(fact(r)*fact(n-r));
				item = (int)x;
				System.out.print("  " +  item);
			}
			System.out.println("");
		}
	}
	
	public static long fact(int a){
		if(a <= 0)
			return (1);
		else
			return (a * fact(a-1));
	}
}

… from College notes (BCA/MCA assignments):


Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: