Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Create a program to calculate factorial of a given number using recursion

  1. import java.io.*;
  2.  
  3. class factorial
  4. {
  5.  long Factorial(int a)
  6.  {
  7.   if(a == 1)
  8.    return 1;
  9.   else
  10.    return(a*Factorial(a-1));
  11.  }
  12. }
  13.  
  14. class CalculateFactorial
  15. {
  16.  public static void main(String args[])
  17.  {
  18.   DataInputStream in = new DataInputStream(System.in);
  19.   int number;
  20.   long answer;
  21.  
  22.   try
  23.   {
  24.    factorial f1 = new factorial();
  25.    System.out.print("Enter Number: ");
  26.    number = Integer.parseInt(in.readLine());
  27.    
  28.    if(number > 0){
  29.     answer = f1.Factorial(number);
  30.     System.out.println("Factorial is : " + answer);
  31.    }
  32.    else{
  33.     System.out.println("Invalid Number");
  34.    }
  35.    
  36.   }
  37.   catch(Exception e)
  38.   {
  39.    System.out.println("Exception" + e);
  40.    System.exit(1);
  41.   }
  42.  }
  43. }
No votes yet
Share this

Post new comment