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 a 2D array (jagged array for varying row lengths) int[][] triangle = new int[numRows][]; // Step 3: Iterate through each row to populate the triangle for (int i = 0; i < numRows; i++) { // Each row 'i' has 'i + 1' elements triangle[i] = new int[i + 1]; // The first and last elements of each row are always 1 triangle[i][0] = 1; triangle[i][i] = 1; // Step 4: Calculate the intermediate elements for rows > 1 for (int j = 1; j < i; j++) { triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; } } // Step 5: Print the Pascal's Triangle System.out.println("\nPascal's Triangle (" + numRows + " rows):"); for (int i = 0; i < numRows; i++) { // Add leading spaces for proper alignment for (int k = 0; k < numRows - i - 1; k++) { System.out.print(" "); } for (int j = 0; j <= i; j++) { System.out.print(triangle[i][j] + " "); } System.out.println(); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS