What is recursion in C++ with Example?
A programming Technique in which a function calls itself is known as recursion in C++. A function that calls itself is called recursive function. The recursion is a powerful technique.
Factorial Using Recursion in C++
The calculation of factorial of a number is a simple example of a recursive technique.
Suppose the factorial of 5 is to be calculated.
The recursive solution to this problem can be shown as follows:
The Above figure shows that factorial can be calculated by decomposing the problem.
The factorial of 5 can be calculated by multiplying 5 with the factorial of 4.
The factorial of 4 can be calculated by multiplying 4 with the factorial of 3 and so on.
The above procedure can be implemented as follows:
int Factorial(unsigned int n)
The following table provides a trace of different calls to the Factorial Function:
A recursive function must have at least one termination condition that can be satisfied.
Otherwise, the function will call itself indefinitely.
The Factorial function has the termination condition n==0 that causes the recursive calls to move back.
programming Example of Recursion
Write a program that inputs a number from the user and calculates its factorial recursively.
long int fact(int n)
cout<<“Enter an integer”;
cout<<“Factorial of <<num<<“is”<<fact(num)”;
Enter an integer 5
Factorial of 5 is 120
Write a program that inputs two integers and calculates the first number raised to the power of the second number recursively.
int power(int x, int n)
int a, b;
cout<<“Enter two integers”;
Enter two integers 2 5