Here is a C++ program to calculate factorial of a number using for loop. Factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n. Factorial is undefined for negative numbers and factorial of 0 is equal to 1. The n! represents the number of ways to arrange n distinct objects into a sequence.
C++ program to find factorial of a number using loop
#include <iostream> using namespace std; int main(){ int N, factorial = 1, i; cout << "Enter a number for factorial calculation\n"; cin >> N; /* * N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1 */ for(i = 1; i <= N; i++){ factorial = factorial * i; } cout << "Factorial of " << N << " is " << factorial; return 0; }Output
Enter a number for factorial calculation 4 Factorial of 4 is 24
Enter a number for factorial calculation 0 Factorial of 0 is 1
C++ program to find factorial of a number using recursion
We can use recursion to calculate factorial of a number because factorial calculation obeys recursive sub-structure property. Let getFactorial(N) is a function to calculate and return value of N!. To find getFactorial(N) we can first calculate getFactorial(N-1) then multiply it with N.
N! = 1 x 2 x 3 x 4....x (N-2) x (N-1) x N
N! = (N-1)! x N
getFactorial(N) = getFactorial(N-1) x N
Function getFactorial(N) reduces the problem of finding factorial of a number N into sub-problem of finding factorial on N-1. It keeps on reducing the domain of the problem until N becomes zero.
#include <iostream> using namespace std; int getFactorial(int N); int main(){ int N; cout << "Enter a Number\n"; cin >> N; cout << "Factorial of " << N << " = " << getFactorial(N); return 0; } // Recursive function to find factorial of a number int getFactorial(int N){ // Recursion Termination condition if(N <= 1){ return 1; } return N * getFactorial(N - 1); }Output
Enter a Number 7 Factorial of 7 = 5040
Recommended Posts