Java Online Compiler
Example: Pascal's Triangle with Space Optimization (1D Array) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle with Space Optimization (1D 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 1D array to store the current row // The maximum length of a row will be numRows int[] currentRow = new int[numRows]; System.out.println("\nPascal's Triangle (" + numRows + " rows):"); // Step 3: Iterate through each row to calculate and print 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(" "); } // Step 4: Calculate elements for the current row, iterating backward // This is crucial to use the values from the *previous* iteration (previous row) // before they are overwritten for the current row's calculation. for (int j = i; j >= 0; j--) { if (j == 0 || j == i) { currentRow[j] = 1; // First and last element are always 1 } else { currentRow[j] = currentRow[j - 1] + currentRow[j]; } } // Step 5: Print the current row for (int j = 0; j <= i; j++) { System.out.print(currentRow[j] + " "); } System.out.println(); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS