Factorial Calculator in Java: Loops and Recursion
Java Project - Factorial Calculation:
Factorial Calculator :
Calculate the factorial of a number using loops or recursion.
This project calculates the factorial of a given number using either loops or recursion. The factorial of a number is the product of all positive integers up to that number.
Input: A number.
Output: Factorial of the number.
Example:
- Input: 5
- Output: 120
Solution 1: Factorial Calculation using Loops
Code:
Output:
Enter a number: 6 Factorial of 6 is: 720
Explanation :
- Input and Scanner: The program takes an integer input from the user.
- Factorial Initialization: A variable factorial is initialized to 1 to store the result.
- For Loop:| The loop runs from 1 to the input number, multiplying the factorial variable by each value of the loop counter.
- Display Result: After the loop ends, the factorial result is displayed to the user.
- Close Scanner: The scanner is closed to free up system resources.
Solution 2: Factorial Calculation using Recursion
Code:
Output:
Enter a number: 7 Factorial of 7 is: 5040
Explanation:
- Input and Scanner: The program takes an integer input from the user.
- Recursive Function: The calculateFactorial() method is a recursive function that calls itself until the base case (n == 0 or n == 1) is reached.
- Base Case: The factorial of 0 or 1 is returned as 1.
- Recursive Call: For other values of n, the function multiplies n by the factorial of n-1.
- Display Result: After the recursive function completes, the result is displayed to the user.
- Close Scanner: The scanner is closed to free up system resources.
Java Code Editor:
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics