Recursive Factorial Program in Java

  • 0
Recursion is the process in which a function calls itself. Generally, iterative programs are slower than corresponding iterative versions of the same program but recursion has found its use due to the fact that sometimes, it is easier to develop recursive version of the program than to develop a iterative version of the same program. The general condition for the recursive program is to have a condition that should fail at some point in the program and at that point, the program needs to traverse back to generate the final answer. Without this condition, your program may fall into an infinite loop, so, the program will never stop unless the stack of method calls is overflowed.

Recursive version of the factorial in Java is given as
package MathUtility;

class FactorialRecursive
{
 int fact(int i)
 {
  if(i==1)
   return 1;
  else
   return i*fact(i-1);
 }
 
 public static void main(String args[])
 {
  int i;
  i = Integer.parseInt(args[0]);
   
  FactorialRecursive fr = new FactorialRecursive();
  System.out.println("Factorial of the number is " + fr.fact(i));
 }
}
To compile the program,
javac -d . FactorialRecursive.java
And to run the program
java MathUtility.FactorialRecursive 9

No comments:

Post a Comment