Hello dear Jetto Developers
How would you like to learn the factorial calculation algorithm in Java programming language? Here is a guide on how to do it in basic steps:
First of all, a factorial is the product of all positive integers between a number itself and 1. For example, the factorial of 5 is calculated as follows: 5! = 5 x 4 x 3 x 3 x 2 x 2 x 1 = 120. The algorithm for factorial calculation can be performed recursively or in a loop. In this article, I will explain factorial calculation with recursive.
Recursive in the most general sense is the iteration of a structure (by itself). In the programming world, if a method calls itself again and again within itself, this method is referred to as a recursive method.
Now let's start writing the program:
First, we will get a number from the user and assign it to the variable sayi. This will be done in the main method at the beginning of the program.
We will then pass the value entered by the user as a parameter to the factorial calculation function and call this function.
Now we will prepare our method. Since we will call our method from the main method, we specify it as static and give it the int value because it will return a value.
We add a condition block to return 1 if the entered number is 0.
When the entered number is not zero, the else block will be executed. This part is the main logic of the factorial calculation function. If the incoming number is other than 0, the function calls itself again and passes the value (n-1) as a parameter to the factorialCalculate function. This process continues until the value of n is 0 and finally the factorial is obtained and the value is returned.
So, we have completed the factorial calculation. You can also calculate it with the loop structure. You can write how you did it in the comments. You can also write your questions.
Thank you for reading this far.
All Codes:
Java
Display Moreimport java.util.Scanner; public class FactorialCalculation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number whose factorial you want to calculate: "); int number = scanner.nextInt(); System.out.println("Factorial of the number you entered: " + faktoriyelHesapla(number)); } public static int calculateFactorial(int n) { if (n == 0) { return 1; } else { return n * calculateFactorial(n - 1); } } }