This java
program finds factorial of a number. Factorial of a number is the
product of all positive descending integers.
For
Example:
6! = 6*5*4*3*2*1 = 720
Java Program to Find Factorial of a Number
import java.util.Scanner;
class JavaFactorial
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to find factorial : ");
int num = sc.nextInt();
long factorial = 1;
for(int i = num; i > 0; --i)
{
factorial *= i;
}
System.out.print("Factorial of "+num+" is "+factorial);
}
}
Output:
Enter a number to find factorial : 6
Factorial of 6 is 720
Java Program to Find Factorial of a Number Using Recursion
import java.util.Scanner;
class JavaFactorial
{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to find factorial : ");
int num = sc.nextInt();
long factorial = factorial(num);
System.out.print("Factorial of "+num+" is "+factorial);
}
}
Output:
Enter a number to find factorial : 6
Factorial of 6 is 720
0 comments:
Post a Comment