As I have discussed in my previous blog that a function that repeats itself is called recursion.So, today I am here with a very common example of recursion in C++. In this example, I will find the factorial of a given number by recursion.Below is the source code of this program.
Source code
- #include <iostream>
- using namespace std;
- int factorial(int);
- int main() {
- int n;
- cout<<"Enter a number: ";
- cin>>n;
- cout<<"Factorial="<<factorial(n);
- return 0;
- }
- int factorial(int n) {
- if (n>1) {
- return n*factorial(n-1);
- }
- else {
- return 1;
- }
- }
Output
Explanation
Suppose user enters 4 which is passed to function
factorial()
. Here are the steps involved:- In first
factorial()
function, test expression inside if statement is true. The statementreturn num*factorial(num-1);
is executed, which calls secondfactorial()
function and argument passed isnum-1
which is 3. - In second
factorial()
function, test expression inside if statement is true. The statementreturn num*factorial(num-1);
is executed, which calls thirdfactorial()
function and argument passed isnum-1
which is 2. - In third
factorial()
function, test expression inside if statement is true. The statementreturn num*factorial(num-1);
is executed, which calls fourthfactorial()
function and argument passed isnum-1
which is 1. - The fourth
factorial()
function, test expression inside if statement is false. The statementreturn 1;
is executed, which returns 1 to thirdfactorial()
function. - The thrid
factorial()
function returns 2 to secondfactorial()
function. - The second
factorial()
function returns 6 to firstfactorial()
function. - Finally, first
factorial()
function returns 24 to themain()
function and is displayed. ( The above reference has been taken from www.programiz.com)
No comments:
Post a Comment