Factorial Using Recursion

Factorial

factorial of any number is calculated in the following way.

n! = 1*2*3*4*5*……….*n

but there is some rule or important point related to factorial

factorial of 0 is 1, so we can use this as a termination for recursion

Recursive Function/Method to Calculate Factorial

int factorial (n)

{

if(n==0)

return 1;

else return n* factorial(n-1);

}

Java Code to Calculate Factorial Using Recursion

import java.util.Scanner;
public class FactorialUsingRecursion{

        // recursive method to calculate factorial
        static int factorial(int n)
        {
            if(n==0)
                return 1;
            else return n*factorial(n-1);
        }

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter any non negative integer to calculate factorial");
            int n = sc.nextInt();
            System.out.println("factorial of "+n+"  is "+factorial(n));
        }
    }

Output –

Java code to calculate factorial using recursion

Factorial of 12 is calculated by multiplying 12*11*10*9*8*7*6*5*4*3*2*1*1

we can use this same logic in all other programming languages like C, C++,Python etc to calculate factorial using recursion.

Similar Java Tutorials

Leave a Comment