Java program to find factorial of given number using recursion

Recursion  is a method where the solution to a problem depends on solutions to smaller instances of the same problem.One of the classic problems for introducing recursion is calculating the factorial of an integer. The factorial of any given integer — call it — is the product of all the integers from 1 to n. Thus, the factorial of 7 is 5040:7x6x 5 x 4 x 3 x 2 x 1.

Here’s the recursive version of the factorial method:

public static int factorial(int n)
{
    if (n <= 1)
        return 1;
    else
        return n * factorial(n-1);
}
<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * java program to find factorial using recursion
 * Created by sani kamal on 07-May-17.
 */

public class Factorial {
    public static void main(String[] args) {
        Factorial fl = new Factorial();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter number to find factorial(less than 20):");
            int n=Integer.parseInt(br.readLine());
            System.out.println("Factorial of "+n+" is:" + fl.factorial(n));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    public int factorial(int num) {
        if (num <= 1) {
            return 1;
        }
        return num * factorial(num - 1);
    }
}</pre>
Advertisements

One thought on “Java program to find factorial of given number using recursion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s