write a Java program to display the factorial of any ten numbers.
Answers
Explanation:
In Layman’s term, Factorial of a positive integer is the product of all descending integers. Factorial of a number(n) is denoted by n!. Also, factorial of 0 is 1 and it is not defined for negative integers. Here’s a simple representation to calculate factorial of a number-
n! = n*(n-1)*(n-2)* . . . . . *1
There are multiple ways to find factorial in Java, which is listed below-
Factorial program in Java using for loop
Factorial program in Java using while loop
Factorial program in Java using recursion
Factorial Program using For Loop
This is one of the easiest programs to find factorial of a number using ‘For Loop’.
This is one of the easiest programs to find factorial of a number using ‘For Loop’. Let’s dive into an example and find a factorial of a given input-
public class FactorialProgram
{
public static void main(String args[]){
int number = 5; // user-defined input to find factorial long fact = 1; // defining fact=1 since least value is 1 int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" = "+fact);
}
}
Output: Factorial of 5 = 120
Explanation: The number whose factorial is to be found is taken as input and stored in a variable ‘number’. Here, we have initialized fact=1 since least value is 1. Then, we’ve used for loop to loop through all the numbers between 1 and the input number(5), where the product of each number is stored in a variable ‘fact’.
Note: The logic of the factorial program remains the same, but the execution differs
Example 1: Find Factorial of a number using for loop
public class Factorial {
public static void main(String[ ] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d =
%d", num, factorial);
}
}