
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Factorial Program 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 4 is 24.
4! = 4 * 3 * 2 *1 4! = 24
The factorial of an integer can be found using a recursive program or an iterative program.
The following program demonstrates a recursive program to find the factorial of a number −
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() { int n = 4; cout<<"Factorial of "<<n<<" is "<<fact(n); return 0; }
Output
Factorial of 4 is 24
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 "<<n<<" is "<<fact(n);
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.
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); }
Advertisements