Site icon

Print Pascal Triangle in Java

What is pascal triangle?

Pascal’s Triangle is like a pyramid made of numbers. It starts with a single number, 1, at the very top. Then, each row below is made by adding the two numbers above it. So, you’d have 1 1, then 1 2 1, and it keeps going on like that.

Each number in pascal triangle is made by adding the two numbers right above it. That’s why it’s so useful in many math things—it shows patterns and helps solve problems in a simpler way. You’ll see it popping up in different parts of math because it’s like a secret code that helps us understand how numbers work together.

Pascal Triangle

Why is it called pascal’s triangle?

Pascal’s Triangle is named after Blaise Pascal, a French mathematician, philosopher, and physicist. While Pascal did not invent the triangle, he significantly contributed to its study and popularization in the Western world.

The triangle’s pattern and properties were known in different cultures and eras, notably in China, Persia, and Europe, before Pascal’s time. However, Pascal introduced and elaborated on the triangle’s properties in his work “Treatise on the Arithmetical Triangle,” published in 1653. His contributions to the study of the triangle’s properties and applications in mathematics led to its association with his name.

Approach: Print Pascal Triangle in Java?

Develop: Write a program to print Pascal Triangle in Java

import java.util.Scanner;

public class PascalTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of rows for Pascal's Triangle: ");
        int numRows = scanner.nextInt();

        for (int i = 0; i < numRows; i++) {
            int number = 1;
            for (int j = 0; j < numRows - i; j++) {
                System.out.print("   "); // Add spaces for alignment
            }
            for (int k = 0; k <= i; k++) {
                System.out.printf("%6d", number);
                number = number * (i - k) / (k + 1);
            }
            System.out.println();
        }
    }
}

Output: Pascal triangle in Java

Enter the number of rows for Pascal's Triangle: 5
                    1
                 1     1
              1     2     1
           1     3     3     1
        1     4     6     4     1

Enter the number of rows for Pascal's Triangle: 8
                             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
Exit mobile version