Java program for Factorial - to find Factorial of a Number.
Factorial of an Integer Number - This program will read an integer number and find the factorial of given integer number.
Find Factorial of a Number using Java program
/*Java program for Factorial - to find Factorial of a Number.*/
import java.util.*;
public class Factorial
{
public static void main(String args[]){
int num;
long factorial;
Scanner bf=new Scanner(System.in);
//input an integer number
System.out.print("Enter any integer number: ");
num= bf.nextInt();
//find factorial
factorial=1;
for(int loop=num; loop>=1; loop--)
factorial*=loop;
System.out.println("Factorial of " + num + " is: " + factorial);
}
}
[email protected]:~$ javac Factorial.java
[email protected]:~$ java Factorial
Enter any integer number: 7
Factorial of 7 is: 5040
Using function/Method
//Java program for Factorial - to find Factorial of a Number.
import java.util.*;
public class Factorial
{
//function to find factorial
public static long findFactorial(int num)
{
long fact=1;
for(int loop=num; loop>=1; loop--)
fact*=loop;
return fact;
}
public static void main(String args[]){
int num;
long factorial;
Scanner bf=new Scanner(System.in);
/*input an integer number*/
System.out.print("Enter any integer number: ");
num= bf.nextInt();
/*find factorial*/
factorial=findFactorial(num);
System.out.println("Factorial of " + num + " is: " + factorial);
}
}