• Home
  • 6.15 Recursive Functions

6.15 Recursive Functions

View Categories

6.15 Recursive Functions

1 min read

Table of Contents

A recursive function is a function that calls itself during its execution. Recursion allows a problem to be divided into smaller instances of the same problem until a condition is reached that stops further recursive calls.

A recursive function requires a base case to terminate the recursion. Without an appropriate base case, the function continues calling itself until the available call stack is exhausted.

Source Code #

#include <iostream>

int factorial(int number)
{
    if (number <= 1)
    {
        return 1;
    }

    return number * factorial(number - 1);
}

int main()
{
    int result = factorial(5);

    std::cout << "Factorial: " << result << '\n';

    return 0;
}

Output #

Factorial: 120

Explanation #

  • factorial() is a recursive function because it calls itself.
  • The condition number <= 1 is the base case that terminates the recursion.
  • When the base case is reached, the function returns 1 without making another recursive call.
  • factorial(number - 1) creates a recursive call using a smaller value of number.
  • For factorial(5), the recursive calls proceed as:factorial(5) factorial(4) factorial(3) factorial(2) factorial(1)
  • factorial(1) reaches the base case and returns 1.
  • The pending function calls then return their results:5 × 4 × 3 × 2 × 1 = 120
  • Each recursive call requires additional stack storage until that call returns.
  • A recursive function must have a terminating condition to prevent unbounded recursion.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *