Saturday, 4 November 2023

Write a Java program to calculate factorial of a number using recursion.-core java slip22

 

Write a Java program to calculate factorial of a number using recursion.

 

import java.util.Scanner;

 

public class FactorialCalculator {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter a non-negative integer to calculate its factorial: ");

        int n = scanner.nextInt();

 

        if (n < 0) {

            System.out.println("Factorial is not defined for negative numbers.");

        } else {

            long factorial = calculateFactorial(n);

            System.out.println("Factorial of " + n + " is: " + factorial);

        }

    }

 

    public static long calculateFactorial(int n) {

        if (n == 0 || n == 1) {

            return 1;

        } else {

            return n * calculateFactorial(n - 1);

        }

    }

}