C++ Recursion

In this lesson, we will learn about recursive functions in C++ and how they operate, with examples, to understand the topic.


What is Recursion?

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
}

C++ Recursion examples

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.


Positive aspects of C++ recursion

  • It streamlines and shortens our code.
  • The programmer needs to define the base case and recursive case.
  • Time complexity can be lowered by recursion.
  • Recursion is necessary for situations involving data structures and sophisticated algorithms, such as Graph and Tree Traversal.

Negative aspects of C++ recursion

  • Compared to an iterative program, it consumes a lot of stack space.
  • It requires greater processing power.
  • Compared to a similar iterative program, debugging may be more challenging.

This concludes the C++ Recursion lesson. In The next lesson, you will learn about Object Oriented Programming in C++.