Java Online Compiler
Example: Pascal's Triangle using While Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle using While Loop 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) { // Step 1: Initialize a Scanner for user input Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); scanner.close(); // Step 2: Create a list to store all rows of the triangle List<List<Integer>> pascalTriangle = new ArrayList<>(); // Step 3: Outer while loop to iterate through each row int currentRowNum = 0; while (currentRowNum < numRows) { // Create a list for the current row List<Integer> currentRow = new ArrayList<>(); // Inner while loop to populate elements of the current row int elementIndex = 0; while (elementIndex <= currentRowNum) { // The first and last elements of each row are always 1 if (elementIndex == 0 || elementIndex == currentRowNum) { currentRow.add(1); } else { // For other elements, sum the two numbers from the previous row // specifically, the element at (elementIndex-1) and (elementIndex) List<Integer> prevRow = pascalTriangle.get(currentRowNum - 1); int sum = prevRow.get(elementIndex - 1) + prevRow.get(elementIndex); currentRow.add(sum); } elementIndex++; } // Add the completed current row to the pascalTriangle list pascalTriangle.add(currentRow); currentRowNum++; // Move to the next row } // Step 4: Print the Pascal's Triangle int i = 0; while (i < pascalTriangle.size()) { List<Integer> rowToPrint = pascalTriangle.get(i); int j = 0; while (j < rowToPrint.size()) { System.out.print(rowToPrint.get(j) + " "); j++; } System.out.println(); // Move to the next line after printing a row i++; } } }
Output
Clear
ADVERTISEMENTS