Monday 19 September 2011

Java Factorial Using Recursion Example

Java Factorial Using Recursion Example

Submitted By: Mohit Garg

  1. /*
  2. Java Factorial Using Recursion Example
  3. This Java example shows how to generate factorial of a given number
  4. using recursive function.
  5. */
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10.  
  11. public class JavaFactorialUsingRecursion {
  12.  
  13. public static void main(String args[]) throws NumberFormatException, IOException{
  14.  
  15. System.out.println("Enter the number: ");
  16.  
  17. //get input from the user
  18. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  19. int a = Integer.parseInt(br.readLine());
  20.  
  21. //call the recursive function to generate factorial
  22. int result= fact(a);
  23.  
  24.  
  25. System.out.println("Factorial of the number is: " + result);
  26. }
  27.  
  28. static int fact(int b)
  29. {
  30. if(b <= 1)
  31. //if the number is 1 then return 1
  32. return 1;
  33. else
  34. //else call the same function with the value - 1
  35. return b * fact(b-1);
  36. }
  37. }
  38.  
  39. /*
  40. Output of this Java example would be
  41.  
  42. Enter the number:
  43. 5
  44. Factorial of the number is: 120
  45. */

No comments:

Post a Comment

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com