Search Java Programs

Tuesday, January 19, 2010

calculate factorial of any given number

Here is the code of the program:
import java.io.*;
class Factorial{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
int fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){}
}
}

Download this example.

Updated Example description

This is the updated example of factorial that will evaluates the factorial of number in double which is lies in the range of double data type in java.

Here is the code of program:

import java.io.*;

class Factorial1{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
double fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){
System.out.println("Array out of bounds exaception");
}
}
}
Download this example.

No comments:

Post a Comment

Website Design by Mayuri Multimedia