JAVA PROGRAM TO DEMONSTRATE THE FACTORIAL OF THE NUMBER


 



///JAVA PROGRAM TO DEMONSTRATE THE FACTORIAL OF THE NUMBER:-

public class FactorialExample {
    public static void main(String[] args) {
        int num = 6; // The number for which factorial is calculated
        int fact = factorial(num); // Call the factorial function and store the result in 'fact'
        System.out.println(fact); // Print the factorial result
    }

    // Recursive function to calculate factorial
    static int factorial(int num) {
        // Base case: If num is 1 or less, factorial is 1
        if (num <= 1) {
            return 1;
        } else {
            // Recursive case: Multiply num with the factorial of num-1
            return (num * factorial(num - 1));
        }
    }
}

Explanation:

  1. The main method is the entry point of the program. It initializes the num variable to 6 and then calls the factorial function with this value. 
  2. The factorial function is a recursive function that calculates the factorial of the input num. In the factorial function, the base case is when num is 1 or less.
  3.  In this case, the function returns 1, as the factorial of 1 is 1. In the recursive case, the function multiplies num with the result of the factorial function called with num - 1.
  4.  This recursive call breaks down the problem into smaller subproblems until it reaches the base case. 
  5. The result of the recursive call is eventually multiplied with the original num, effectively calculating the factorial. The main method then prints the calculated factorial using System.out.println. 
When you run this code, it will output:

720
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.