Java Online Compiler
Example: Factorial with Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Factorial with Recursion import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive method to calculate factorial public static long calculateFactorial(int n) { // Step 1: Define the base case // The factorial of 0 or 1 is 1 if (n == 0 || n == 1) { return 1; } // Step 2: Define the recursive step // n! = n * (n-1)! else { return n * calculateFactorial(n - 1); } } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a non-negative integer System.out.print("Enter a non-negative integer: "); int number = scanner.nextInt(); // Step 3: Validate the input to ensure it's non-negative if (number < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { // Step 4: Calculate the factorial using the recursive method long factorialResult = calculateFactorial(number); // Step 5: Display the result System.out.println("The factorial of " + number + " is: " + factorialResult); } // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS