Java Online Compiler
Example: Pascal's Triangle using 2D Array in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle using 2D Array import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get the number of rows from the user System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); // Step 2: Declare and initialize the 2D array (jagged array) int[][] pascalTriangle = new int[numRows][]; // Step 3: Populate the Pascal's Triangle for (int i = 0; i < numRows; i++) { // Each row 'i' has 'i + 1' elements pascalTriangle[i] = new int[i + 1]; // The first and last elements of each row are always 1 pascalTriangle[i][0] = 1; if (i > 0) { pascalTriangle[i][i] = 1; } // Calculate the inner elements of the current row // An element is the sum of the two elements directly above it for (int j = 1; j < i; j++) { pascalTriangle[i][j] = pascalTriangle[i-1][j-1] + pascalTriangle[i-1][j]; } } // Step 4: Print the Pascal's Triangle System.out.println("\nPascal's Triangle with " + numRows + " rows:"); for (int i = 0; i < numRows; i++) { // Add leading spaces for proper triangular alignment for (int k = 0; k < numRows - 1 - i; k++) { System.out.print(" "); // Adjust spacing as needed } for (int j = 0; j < pascalTriangle[i].length; j++) { System.out.printf("%4d", pascalTriangle[i][j]); // Print with formatting } System.out.println(); // Move to the next line for the next row } scanner.close(); } }
Output
Clear
ADVERTISEMENTS