Java Program to calculate factorial of a number by recursion

Input

Number whose factorial is to be calculated by recursion.

Example: 3

Program Code

package programs.java4newbie.com;

/*
This Program calculates the factorial of the number by recursion
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FactorialByRecursion {

public static void main(String args[]) throws NumberFormatException, IOException{

System.out.println("Enter the number whose factorial is to be calculated: ");

//get input from the user
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());

//call the recursive function to generate factorial
int result= factorial(a);

System.out.println("Factorial of the number is: " + result);
}

static int factorial(int a)
{
if(a <= 1)
//if the number is 1 then return 1, since factorial of 1 is 1
return 1;
else
//else call the same function by recursion
return a * factorial(a-1);
}
}

Output

Enter the number:
3
Factorial of the number is: 6