Thursday, 23 June 2011

Java Program to takes value from user and finds its factorial


Open notepad or any text editor and type this code.

import java.io.*;

class fact
  {
    public static void main(String args[]) throws IOException
     {
        BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the no.: ");
        String a;
        int c=1;
        a=ob.readLine();
        int i=Integer.parseInt(a);

        while(i>0)
          {
           c=c*i;
           i--;
          }
            System.out.print("The factorial of "+a+" is: "+c);
      }
    }           

and save this file as fact.java in the bin directory (c:\j2sdk1.4.2\bin).

Now open command prompt and go to your Java directory.
Now compile your  program by typing  javac fact.java
Now the program will be compiled.
Now Run your program by typing  java fact

The output of the above program will be like this.

No comments:

Post a Comment