Java Program to Print a Pascal's Triangle

1. Introduction

In this tutorial, we'll be creating a Java program to print Pascal's Triangle, a triangular array of the binomial coefficients. This program is a great way to understand loops, arrays, and the mathematical logic behind Pascal's Triangle. By incorporating user input, the program allows for dynamic generation of the triangle up to the number of rows specified by the user, making it interactive and flexible.

2. Program Steps

1. Import the Scanner class for reading user input.

2. Prompt the user to enter the number of rows for Pascal's Triangle.

3. Initialize an array to store the values of the triangle.

4. Use nested loops to calculate the values of each row based on the values of the previous row and print the triangle.

5. Compile and run the program, then enter the desired number of rows to generate Pascal's Triangle.

3. Code Program

import java.util.Scanner; // Import Scanner class

public class PascalsTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(; // Create Scanner object
        System.out.print("Enter the number of rows: "); // Prompt for user input
        int rows = scanner.nextInt(); // Read number of rows from user

        for(int i = 0; i < rows; i++) {
            int number = 1;
            System.out.format("%" + (rows - i) * 2 + "s", ""); // Align the triangle
            for(int j = 0; j <= i; j++) {
                System.out.format("%4d", number); // Print each number in the row
                number = number * (i - j) / (j + 1); // Calculate the next number
            System.out.println(); // Move to the next line after each row
        scanner.close(); // Close the scanner


Enter the number of rows: 5
      1   1
    1   2   1
  1   3   3   1
1   4   6   4   1


1. The program starts by importing the Scanner class to allow for user input, which determines the number of rows in Pascal's Triangle.

2. The user is prompted to enter the desired number of rows. This input dictates how large the triangle will be.

3. The program uses a for loop to iterate over each row. At the beginning of each row, it calculates and prints the appropriate amount of leading spaces to center the triangle on the console.

4. Inside this loop, a nested for loop calculates the values of Pascal's Triangle using the binomial coefficient formula. The formula number = number * (i - j) / (j + 1) calculates the next number in the row based on the current number, where i is the row index and j is the column index within the row.

5. The formatted print statement System.out.format("%4d", number) ensures that each number is properly aligned, creating a visually appealing triangle.

6. Finally, the Scanner object is closed to prevent resource leaks, following best practices for resource management in Java programs.