Tuesday, December 13, 2011

Factorial program using recursion in java

import java.util.*;
import java.io.*;
class fact
{
public static void main(String args[])throws Exception
{
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
System.out.println("factorial of "+n+" is:"+factorial(n));
}
static int factorial(int k)
{
if (k == 0)
return 1;
return k * factorial(k-1);
}
}

output:
enter a number
5
factorial of 5 is:120