
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to Calculate Factorial of a Number Using Recursion
Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.
For example: The factorial of 7 is 5040.
7! = 7 * 6 * 5 * 4 * 3 * 2 *1 7! = 5040
Let us see the code to calculate the factorial of a number using recursion.
Example
#include <iostream> using namespace std; int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); } int main() { cout<<"Factorial of 5 is "<<fact(5)<<endl; cout<<"Factorial of 3 is "<<fact(3)<<endl; cout<<"Factorial of 7 is "<<fact(7)<<endl; return 0; }
Output
Factorial of 5 is 120 Factorial of 3 is 6 Factorial of 7 is 5040
In the above program, the function fact() is a recursive function. The main() function calls fact() using the number whose factorial is required. This is demonstrated by the following code snippet.
cout<<"Factorial of 5 is "<<fact(5)<<endl; cout<<"Factorial of 3 is "<<fact(3)<<endl; cout<<"Factorial of 7 is "<<fact(7)<<endl;
If the number is 0 or 1, then fact() returns 1. If the number is any other, then fact() recursively calls itself with the value n-1. Along with calling itself recursively, fact() multiplies n with the recursive call fact(n-1). This yields.
n*(n-1)*(n-2)....3*2*1 or the factorial of n
This is demonstrated using the following code snippet.
int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); }
- Related Articles
- Write a C# program to calculate a factorial using recursion
- C++ Program to Find Factorial of a Number using Recursion
- Java Program to Find Factorial of a Number Using Recursion
- Java program to find the factorial of a given number using recursion
- Write a Golang program to find the factorial of a given number (Using Recursion)
- Python Program to find the factorial of a number without recursion
- Factorial program in Java using recursion.
- Java program to calculate the power of a Given number using recursion
- Java program to calculate the GCD of a given number using recursion
- How to Find Factorial of Number Using Recursion in Python?
- Java program to calculate the factorial of a given number using while loop
- Factorial program in Java without using recursion.
- C++ Program to Calculate Power Using Recursion
- How to calculate Power of a number using recursion in C#?
- Java Program to calculate the power using recursion

Advertisements