In this lesson, we will learn about recursive functions in C++ and how they operate, with examples, to understand the topic.
Recursive functions are defined as those that call themselves repeatedly. This method is called recursion.
void recursion() { recursion(); // The recursion calls itself until base condition is met. } int main() { recursion(); // C++ recursion function call from main once }
Below is an example of Recursion in C++
Function to Calculate Power Number Example:
#include <iostream> using namespace std; int NumberPower(int, int); int main() { int basNumber, pwrNumber, Output; cout << "Please enter base number: "; cin >> basNumber; cout << "Please enter power number: "; cin >> pwrNumber; Output = NumberPower(basNumber, pwrNumber); cout << basNumber << "^" << pwrNumber << " = " << Output; return 0; } int NumberPower(int basNumber, int pwrNumber) { if (pwrNumber != 0) return (basNumber * NumberPower(basNumber, pwrNumber - 1)); else return 1; }
Output
Please enter base number: 6 Please enter power number: 3 6^3 = 216
Because the exponent is always a positive integer, the recursive function NumberPower
calls itself again while checking the power up to 0. The program that uses recursion to calculate a number’s power has an O(logn) running time complexity because each time the recursive function is called, the parameter for the subsequent call increases by an exponential factor. As a result, the log is a function’s time complexity.
The benefits and drawbacks of recursion in C++ are listed below.
This concludes the C++ Recursion lesson. In The next lesson, you will learn about Object Oriented Programming in C++.