Java Factorial Using Recursion

  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. */

0 comments: