Printing patterns with stars or numbers and triangles are some of the the common programming exercises. Earlier we have seen how to print pyramid pattern with stars and today you will learn how to print Pascal's triangle in Java. Sometime this problem is also asked as

Here is the Pascal's triangle with 6 rows, you can see it's not the number but the formatting which is difficult to code.

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

The triangle is named after the famous french mathematician Blaise Pascal who organized detailed information on the triangle in a book. However this triangle was already known to many ancient civilizations.

Pascal’s triangle has many unique properties e.g. the sum of numbers in each row is twice the sum of numbers in the above row and the diagonals adjacent to the border diagonals contains natural numbers in order. Pascal triangle is also related to Fibonacci series, if you add the numbers in Pascal's triangle in diagonal lines going up, you get one of the Fibonacci numbers. Even though the post is about printing the Pascal's triangle but a bit history always helps.

##

Here is the Java program to print Pascal's triangle without using any array. I have encapsulated logic inside a static method so that I can directly call it from main method, as you might know that you can only call static method from main in Java.

The method has two loops because we are printing two dimensional pattern. The outer loop print number of rows in Pascal triangle and the inner loop is responsible for printing numbers in each rows. The complexity of this solution is O(n^2) where n is number of rows.

You should also pay some attention to the formatting commands we have used above to create a nicely formatted triangle. The %4d formatting instruction is used to print the number within 4 spaces. We chosen 4 since we know the maximum number of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.

Btw, if you want more coding problems for practice, you should check Cracking the Coding Interview, which contains more than 189 coding problems from technical companies like Google, Amazon, Facebook, Microsoft, ThoughtWorks, Apple, Twitter, and several other startups.

If you are more interested on learning algorithm, then you should read a good book on data structure and algorithms e.g. Introduction to Algorithm by Thomas Cormen.

That's all about

Alternatively, you can also solve following coding problems from this blog:

**"write a program to print Pascal triangle without using array"**or by just using for loop. Pascal’s triangle is a set of numbers arranged in the form of a triangle, similar to Floyd's triangle but their shape is different. Each number in the Pascal triangle row is the sum of the left number and right number of the previous row. If a number is missing in the above row, it is assumed to be 0. The first row starts with number 1, that's why you will see that first two row of Pascal triangle just contain 1.Here is the Pascal's triangle with 6 rows, you can see it's not the number but the formatting which is difficult to code.

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

The triangle is named after the famous french mathematician Blaise Pascal who organized detailed information on the triangle in a book. However this triangle was already known to many ancient civilizations.

Pascal’s triangle has many unique properties e.g. the sum of numbers in each row is twice the sum of numbers in the above row and the diagonals adjacent to the border diagonals contains natural numbers in order. Pascal triangle is also related to Fibonacci series, if you add the numbers in Pascal's triangle in diagonal lines going up, you get one of the Fibonacci numbers. Even though the post is about printing the Pascal's triangle but a bit history always helps.

##
__Printing Pacal Triangle in Java__

Here is the Java program to print Pascal's triangle without using any array. I have encapsulated logic inside a static method so that I can directly call it from main method, as you might know that you can only call static method from main in Java. The method has two loops because we are printing two dimensional pattern. The outer loop print number of rows in Pascal triangle and the inner loop is responsible for printing numbers in each rows. The complexity of this solution is O(n^2) where n is number of rows.

You should also pay some attention to the formatting commands we have used above to create a nicely formatted triangle. The %4d formatting instruction is used to print the number within 4 spaces. We chosen 4 since we know the maximum number of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.

Btw, if you want more coding problems for practice, you should check Cracking the Coding Interview, which contains more than 189 coding problems from technical companies like Google, Amazon, Facebook, Microsoft, ThoughtWorks, Apple, Twitter, and several other startups.

If you are more interested on learning algorithm, then you should read a good book on data structure and algorithms e.g. Introduction to Algorithm by Thomas Cormen.

Now, here is our sample program in Java to

**print Pascal's triangle**for given number of rows. It accept the number of rows from user via command prompt.import java.util.Scanner; /* * Java Program to print Pascal's triangle for given number of rows * */ public class PascalTriangleInJava { public static void main(String[] args) { System.out.println("Welcome to Java program to print Pascal's triangle"); System.out.println("Please enter number of rows of Pascal's triangle"); // Using try with resource statment to open Scanner // no need to close Scanner later try (Scanner scnr = new Scanner(System.in)) { int rows = scnr.nextInt(); System.out.printf("Pascal's triangle with %d rows %n", rows); printPascalTriangle(rows); } } /** * Java method to print Pascal's triangle for given number of rows * * @param rows */ public static void printPascalTriangle(int rows) { for (int i = 0; i < rows; i++) { int number = 1; System.out.printf("%" + (rows - i) * 2 + "s", ""); for (int j = 0; j <= i; j++) { System.out.printf("%4d", number); number = number * (i - j) / (j + 1); } System.out.println(); } } } Output Welcome to Java program to print Pascal's triangle Please enter number of rows of Pascal's triangle 4 Pascal's triangle with 4 rows 1 1 1 1 2 1 1 3 3 1 Welcome to Java program to print Pascal's triangle Please enter number of rows of Pascal's triangle 7 Pascal's triangle with 7 rows 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

That's all about

**how to print Pascal's triangle in Java**. As I said, it's not a difficult problem, the logic to generate number in each row is simple, each number is sum of number of its left and right in previous row. The only tricky part is to properly format the output. In order to do that, you must know the maximum digit in the maximum number in the Pascal triangle you are printing. This problem assume that it will only print Pascal triangle up-to 10 rows. If you want to practice more problems, see Cracking the Coding Interview book.Alternatively, you can also solve following coding problems from this blog:

- Top 10 Programming problems from Java Interviews? (article)
- How to calculate factorial using recursion and iteration? (solution)
- How do you swap two integers without using a temporary variable? (solution)
- Write a program to check if a number is a power of two or not? (solution)
- How to find duplicate characters from String in Java? (solution)
- Write code to implement Quicksort algorithm in Java? (algorithm)
- How to reverse String in Java without using StringBuffer? (solution)
- Write a program to code insertion sort algorithm in Java (program)
- How to find a missing number in a sorted array? (solution)
- How to solve FizzBuzz problem in Java? (solution)
- How do you reverse word of a sentence in Java? (solution)
- How to find if given String is a palindrome in Java? (solution)
- How to reverse an int variable in Java? (solution)
- Write a program to print the highest frequency word from a text file? (solution)
- Write code to implement Bubble sort algorithm in Java? (code)
- How to check if a given number is prime or not? (solution)
- How to remove duplicate elements from ArrayList in Java? (solution)
- How to check if a year is a leap year in Java? (answer)
- Java Program to print Prime numbers upto 100 (solution)
- Java Program to print Alphabets in upper and lower case? (solution)

System.out.printf("%" + (rows - i) * 2 + "s", "");

ReplyDeletecan u explain me about this line?

please.

best solution

ReplyDeletefor i=0 & rows=5 ...it will concatenate .. "%" (5-0)*2 "s" i.e. %10s ...which gives spaces of 10 characters

ReplyDelete