Wednesday, July 22, 2009

Factorial Program in Java, Java program for finding the Factorial of a number

Hi friends, welcome back to Java Code Online. Today I will give you the Java code for finding the factorial of an entered number. The factorial of a number is the product of all the numbers starting from 1 till that particular number.

The Java code provided asks the user to enter a number for which the factorial is desired. It then uses recursion to find the factorial of that number. Though recursion is not always the best approach for solving a Java problem, since it can lead to core dump or Dr. Watson error in Windows. It implies that if recursion is used improperly, then it can loop again and again into itself, causing stackOverflowError in Java, leading to crashing of the JVM.

The Java Code is provided below:-

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

public class Factorial {

public static void main(String[] args) throws NumberFormatException, IOException {
long num;
System.out.println("Enter a number greater then or equal to 0 and less then 40 for which the factorial is desired:-");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
num = Integer.parseInt(br.readLine());
if(num>=0 && num < 40)
{
if(num == 0)
{
num =1;
}
System.out.println(factorial(num));
}
else
{
System.out.println("Number out of range");
}
}

private static long factorial(long num) {
if(num > 1)
{
num = num * factorial(num-1);
}
else
{
return num;
}
return num;
}
}

I hope that the Java code provided for finding the factorial of a number is useful to you all. If you like the post, then do leave a comment. For more info on Java, keep buzzing Java Code Online.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.