Finding factorial of a number is a very common and mostly asked Java Program in schools or collages.
Lets find out how to find factorial of a number using the given Java program :
Output:
Download my project Factorial
Lets find out how to find factorial of a number using the given Java program :
import java.io.*;
public class factorial {
    public static int fac(int a){
          int num = a;                 
          int result = 1;
          while(num>0){
                result = result * num;
                num--;
          }
          return result;
    }
    public static void main (String args[]){
        InputStreamReader istream = new InputStreamReader(System.in) ;
        BufferedReader bufRead = new BufferedReader(istream) ;
        int num=0;
        System.out.print("Enter Number: ");
        try{
            num=Integer.parseInt( bufRead.readLine() );
            System.out.println("Factorial of "+num+" is : "+fac( num ) );
        }catch( Exception Number ){
            System.out.println("Invalid Number!");
        }
    }
}
Output:
Download my project Factorial
2 Comments Leave new
how can we write this program using scanner class instead of BufferReader..
ReplyHello MANKALA!
ReplyYes we can write this program using scanner.
Source Code:
import java.util.Scanner;
public class factorial {
public static int fac(int a){
int num = a;
int result = 1;
while(num>0){
result = result * num;
num--;
}
return result;
}
public static void main (String args[]){
Scanner scan = new Scanner (System.in);
int num=0;
System.out.print("Enter Number: ");
try{
num = scan.nextInt();
System.out.println("Factorial of "+num+" is : "+fac( num ) );
}catch( Exception Number ){
System.out.println("Invalid Number!");
}
}
}
Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.