
The Factorial using recursion is a popular method of solving problems based on recursion. There are more than one method to solve recursion where we can also use loops to evaluate the factorial value of a number.
In this article, we will learn more about how to use different programming languages to calculate the factorial of a number. We will also learn the logic or algorithm required to solve the factorial number using the recursion method in this blog article.
| factorial(5) = 5 * factorial(4) factorial(4) = 4 * factorial(3) factorial(3) = 3 * factorial(2) factorial(2) = 2 * factorial(1) factorial(1) = 1 (Base case) |
| #include <stdio.h> long long factorial(int n) { if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num < 0) { printf("Factorial is not defined for negative numbers.\n"); } else { printf("Factorial of %d is %lld\n", num, factorial(num)); } return 0; } |
| #include <iostream> using namespace std; long long factorial(int n) { if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } int main() { int num; // Taking input from user cout << "Enter a number: "; cin >> num; if (num < 0) { cout << "Factorial is not defined for negative numbers." << endl; } else { cout << "Factorial of " << num << " is " << factorial(num) << endl; } return |
| import java.util.Scanner; public class FactorialRecursion { // Recursive function to calculate factorial static long factorial(int n) { if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); // Recursive call } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); if (num < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { System.out.println("Factorial of " + num + " is " + factorial(num)); } scanner.close(); } } |
| def factorial(n): if n == 0 or n == 1: return 1 # Base case: Factorial of 0 or 1 is 1 return n * factorial(n - 1) # Taking input from user num = int(input("Enter a number: ")) if num < 0: print("Factorial is not defined for negative numbers.") else: print(f"Factorial of {num} is {factorial(num)}") |