Java Program for Finding Factorial

Java Program for Finding Factorial

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 :


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:
Factorial-output


Download my project Factorial 

2 Comments Leave new

how can we write this program using scanner class instead of BufferReader..

Reply

Hello MANKALA!
Yes 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!");
        }
    }
}

Reply

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.