Go to Top

Sunday, 2 October 2011

To find the factorial of a given number

Question 52 : Write a program in Java to find and print the factorial of a number.

Factorial : Let number be 5

= 5 * 4 * 3 * 2 * 1 = 120

Java Program :

import java.io.*;
class factorial
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int n,i;
     System.out.print("Enter the number : ");
     n=Integer.parseInt(br.readLine());
     int s=n;
     for(i=n-1;i>=1;i--)
     {
         s=s*i;
        }
        System.out.print("\n");
        System.out.println("The result = "+s);
    }
}

2 comments:

  1. import java.io.*;
    class Factorial
    {
    public static void main(String args[])throws IOException
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter any number : ");
    int n=Integer.parseInt(br.readLine());//suppose n=5
    int f=1;
    for(int i=1; i<=n; i++)
    {
    f=f*i; //f=120 (5*4*3*2*1=120)
    }
    System.out.println("Factorial of "+n+" is "+f);
    }
    }

    ReplyDelete

ShareThis