Java Online Compiler
Example: Pascal's Triangle Iterative in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle Iterative import java.util.ArrayList; import java.util.List; 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); System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); // Step 1: Use a list of lists to store the triangle List<List<Integer>> triangle = new ArrayList<>(); // Step 2: Iterate through each row to build the triangle for (int i = 0; i < numRows; i++) { List<Integer> currentRow = new ArrayList<>(); // Step 3: Add leading spaces for proper alignment (for printing only) for (int space = 0; space < numRows - 1 - i; space++) { System.out.print(" "); } // Step 4: Iterate through each element in the current row for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { currentRow.add(1); // The first and last elements of each row are 1 } else { // Current element is the sum of two elements from the previous row int sum = triangle.get(i - 1).get(j - 1) + triangle.get(i - 1).get(j); currentRow.add(sum); } System.out.printf("%4d", currentRow.get(j)); // Print the current element } triangle.add(currentRow); // Add the completed row to the triangle System.out.println(); // Move to the next line } scanner.close(); } }
Output
Clear
ADVERTISEMENTS