Java Online Compiler
Example: Pascal's Triangle using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle using Recursion import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive helper function to calculate the value at a specific position (row, col) public static int pascalValue(int row, int col) { // Step 1: Base Cases // The first and last elements of each row are always 1. // Also handles the top of the triangle (row 0, col 0). if (col == 0 || col == row) { return 1; } // Step 2: Recursive Step // Any other element is the sum of the two elements directly above it // (one from the previous row at the same column, and one from the previous row at the previous column). return pascalValue(row - 1, col - 1) + pascalValue(row - 1, col); } public static void main(String[] args) { // Step 1: Prompt user for the number of rows Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); scanner.close(); System.out.println("Pascal's Triangle (recursive):"); // Step 2: Iterate through each row to print the triangle for (int i = 0; i < numRows; i++) { // Step 3: Print leading spaces for formatting // This centers the triangle visually. for (int k = 0; k < numRows - i; k++) { System.out.print(" "); } // Step 4: Iterate through each column in the current row for (int j = 0; j <= i; j++) { // Step 5: Calculate and print the value using the recursive helper function System.out.print(pascalValue(i, j) + " "); } System.out.println(); // Move to the next line after printing each row } } }
Output
Clear
ADVERTISEMENTS