Monday 12 September 2011

Write a program to calculate factorial of any given number

This Java programming tutorial will teach you the methods for writing program to calculate factorial of any given number. First of all define a class "Factorial" under the Java I/O package. Java I/O package has a input stream and a output stream in which input stream is used for reading the stream and memory allocating and the output stream is used for writing bytes. As in this program we are going to insert certain instruction by creating buffer reader class, it is necessary to use 'try' and 'catch' block for catching and handling exceptions during execution of the program.  
Here, we have to create a buffer for the string class that can be used to instantiate a changeable object for storing and processing a string of character. The strings length and content change as soon as any object is inserted, replaced or removed from the StringBuffer object. 
Now create a buffer object that inherits properties from the string object class. Now create an InputStreamReader that reads bytes and decodes them into character by using certain 'charset'. Now use the ParseInt method for converting the parses the string argument to a decimal integer and define 'a' as an integer. Take an integer variable as fact=1 and insert the message in the System method. 
Now applying for loop with conditions as integer i=1(intializer),  i<=a and i++ as increment operator. So output result will be like fact=fact*i.
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: