In this tutorial you will learn about the Java Program to Find Factorial of a Number and its application with practical example.
Java Program to Find Factorial of a Number
In this tutorial, we will learn to create a Java program that will Find Factorial of a Number using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- Conditional Statements in Java programming.
- Arithmetic operations in Java Programming.
What is factorial?
The factorial means the product of the input number and its below integer value up to 1.
1 2 3 4 5 |
For example:- Factorial of 5 means Factorial = 5 * 4 * 3 * 2 * 1 Hence, the factorial will be 120. |
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the required variables for the program. 2. Sending message to enter a number for finding the factorial of the number. 3. Taking the input number from the user for factorial. 4. Calculating Factorial of a Number Using Recursion of that number. 5. Printing the result numbers. 6. End Program. |
Program to Calculate Factorial:-
In today’s tutorial, we will learn to create a program that will find the factorial of a number. First, we will take a number in input from the user. Then we will find the factorial using the for-loop. At last, we will print the factorial of the given number to the user.
Program Code:–
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Factorial { public static void main(String[] args) { //Declaring the required variables for the program. int no = 10; long factorial = 1; int i; //Using the for loop to find the factorial of a number. for(i = 1; i <= no; ++i) { // factorial = factorial * i; factorial *= i; } //Printing the factorial of a number. System.out.printf("Factorial of %d = %d", no, factorial); } } |
Output:-
In the above program, we have first initialized the required variable.
- no = it will hold the integer value.
- i = it will hold the integer value.
- factorial = it will hold the integer value.