Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive factorial method in Java
The factorial of any non-negative integer is basically the product of all the integers that are smaller than or equal to it. The factorial can be obtained using a recursive method.
A program that demonstrates this is given as follows:
Example
public class Demo {
public static long fact(long n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
public static void main(String args[]) {
System.out.println("The factorial of 6 is: " + fact(6));
System.out.println("The factorial of 0 is: " + fact(0));
}
}
Output
The factorial of 6 is: 720 The factorial of 0 is: 1
Now let us understand the above program.
The method fact() calculates the factorial of a number n. If n is less than or equal to 1, it returns 1. Otherwise it recursively calls itself and returns n * fact(n - 1). A code snippet which demonstrates this is as follows:
public static long fact(long n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
In main(), the method fact() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String args[]) {
System.out.println("The factorial of 6 is: " + fact(6));
System.out.println("The factorial of 0 is: " + fact(0));
}Advertisements