Search Your Topic

Friday, 14 July 2017 03:35

Java Factorial Using Recursion Example

Written by
Rate this item
(0 votes)
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 NumberFormatExceptionIOException{
14.
15.                 System.out.println("Enter the number: ");
16.
17.                 //get input from the user
18.                 BufferedReader br=new BufferedReader(newInputStreamReader(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(<= 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. */
Read 1127 times

Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

Call +91 74 88 34 7779  | Email : anishsingh@live.com

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.