TechArena Community (http://forums.techarena.in/)
-   Software Development (http://forums.techarena.in/software-development/)
-   -   How to write java program to find factorial of number? (http://forums.techarena.in/software-development/1276405.htm)

 Balamohan 28-11-2009 09:54 PM

How to write java program to find factorial of number?

Hello,
I am T.Y.B.Sc. student. As per our syllabus we have java programming language. I recently started learning java language. In our last tutorial our sir has said write a java program to find factorial of number. I tried various methods but unable to write that program. Please if you have any idea about this program share with me.

 Zecho 28-11-2009 09:58 PM

Re: How to write java program to find factorial of number?

Code:

```public class FactorialNumber { public static void main(String[] args) { int N = 5; int F = N; for(int p =(N - 1); p > 1; p--) { F = F * p; } System.out.println("Factorial of a number is " + F); } }```

 Reegan 28-11-2009 10:02 PM

Re: How to write java program to find factorial of number?

Don't just copy paste, tried to understand each step.

Code:

```import java.io.*; class FactorialNumber {   public static void main(String[] args) {       try{         BufferedReader obj1 = new BufferedReader(new InputStreamReader(System.in));         System.out.println("Enter the number");         int A= Integer.parseInt(object.readLine());         int F= 1;         System.out.println("Factorial of " +A+ ":");         for (int P= 1; P<=A;P++){               F=F*P;         }         System.out.println(F);     }     catch (Exception e){}   } }```

 opaper 28-11-2009 10:07 PM

Re: How to write java program to find factorial of number?

Here I use recursion method.

Code:

```public class RFactorial {   public static void main( String [] args )   {         System.out.println( "Factorial ( 7 ) is "                       + factorial( 7 ) );   }     public static int factorial( int p )   {     if ( p <= 0 )      return 1;     else        return ( p * factorial ( p - 1 ) );   } }```

 MindSpace 28-11-2009 10:11 PM

Re: How to write java program to find factorial of number?

You can use iterative method to calculate factorial using following code.

Code:

``` int FactorialOfNumber = 1; for (int p = 1; p<= x; p++) FactorialOfNumber *= p;```

 Modifier 28-11-2009 10:14 PM

Re: How to write java program to find factorial of number?

Code:

```  1.       import java.util.*;       public class factorialNumber       {       public static void main(String[]args)       {       int x,F,P;       System.out.println("Factorial ");       System.out.println("Enter the number");       Scanner sc = new Scanner(System.in);       P = sc.nextInt();       x = 1;       F = 1;       F= F * x;       while (x != P)       {       x = x + 1;       }       F = F * x;       System.out.println(F);             }       }```

 All times are GMT +5.5. The time now is 07:32 AM.