I have already explained about recursion in earlier post and shown the example Reverse the string. In this post, we will use recursion method to calculate the factorial of a number.
What is factorial of a number?
Factorial of a number is the product of all numbers counting backwards from the given number till number 1. Suppose number is 5, so factorial of number 5 is equal to 5 * 4 * 3 * 2 * 1
f(5) = 5 * 4 * 3 * 2 * 1
f(4) = 4 * 3 * 2 * 1
f(3) = 3 * 2 * 1
We can notice the pattern to calculate the factorial.
f(n) = n * f(n-1)
We will use this pattern for recursion. The program will call the same method recursively till the number is 1 and then it will calculate the backwards and return the result.
Here is the program -
import java.util.Scanner;
public class FactorialDemo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
int fact = factorial(n);
System.out.println("Factorial of the number " + n + " is: " + fact);
}
public static int factorial(int n) {
int result = n;
if(n != 1)
result = result * factorial(n-1);
return result;
}
}
Here is the output -
Enter the number: 5
Factorial of the number 5 is: 120
The program asks user to enter any number. It passes the number to a method factorial() which calculates the factorial of the number.
- The method factorial() method calls itself recursively by decreasing the number by 1 till the number is 1. It returns 1 when the number is 1.
- Then it multiplies by 2 and then returns result back to the calling method.
- Multiplies by 3 and then returns result back to the calling method.
- And so on till it reaches the original number
- When it reaches the original number, multiplies and it returns the final result back to main method.
Code can be found here on Github.
No comments:
Post a Comment