×

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the many C++ problems that may be broken down into related sub-problems and are usually resolved using recursion.

Working of Recursive Function:

A recursive function is made up of two main parts:

  • Base Case: The situation that prevents an infinite loop from occurring by stopping the recursion.
  • Recursive Case: By invoking itself with a changed parameter, the function progressively gets closer to the basic case.

Key Features of the Recursive Function:

Several key features of the recursive function in C++ are as follows:

1. Base Case and Recursive Case:

  • There must be a base case for each recursive function to halt the recursion.
  • The function itself is called in the recursive scenario with altered parameters.

2. Function Call Stack Usage:

  • The call stack retains each recursive call until the base case is reached.
  • The stack unwinds and all outstanding calls are resolved after the base case returns.

3. Memory and  performance Considerations:

  • Stack frames cause recursive functions to consume more memory.
  • If deep recursion is not managed appropriately, stack overflow may result.

4. Simplicity and Readability:

  • Factorial, tree traversal, and Fibonacci are some examples of simplifications provided by recursion.
  • It lends itself toward simpler and more logical thinking in problem solving.

5. Direct and Indirect Recursion:

  • When a function calls itself directly, such as factorial(n), this is known as direct recursion.
  • When one function calls another, which in turn calls the original function, this is known as an indirect recursion.

Algorithm:

Step 1: Start 

Step 2: Define a function FACTORIAL(n) 

        - If n == 0, return 1 (Base case) 

        - Else, return n * FACTORIAL(n - 1) (Recursive case) 

Step 3: In the main function, take an integer input n 

Step 4: Call FACTORIAL(n) and store the result 

Step 5: Print the result 

Step 6: End 

Pseudo code:

FUNCTION FACTORIAL(n):

    IF n == 0 THEN

        RETURN 1

    ELSE

        RETURN n * FACTORIAL(n - 1)

    ENDIF

END FUNCTION

BEGIN MAIN

    DECLARE num AS INTEGER

    SET num = 5  // Example value

    DECLARE result AS INTEGER

    SET result = FACTORIAL(num)

    PRINT "Factorial of ", num, " is ", result

END MAIN

Example code for Recursive Function:

Example 1: Factorial Function

#include <iostream>

using namespace std;

int factorial(int n) {

    if (n == 0)  // Base case

        return 1;

    return n * factorial(n - 1);  // Recursive case

}

int main() {

    int num = 5;

    cout << "Factorial of " << num << " is " << factorial(num) << endl;

    return 0;

}

Output:

Factorial of 5 is 120

Explanation:

  • The function returns 1 in the base situation when n == 0.
  • If not, it keeps calling itself with n - 1 until it hits 0.

Example 2: Fibonacci Series using Recursion

The Fibonacci sequence starts with 0 and 1 and includes digits that are equal to the sum of two digits before them.

#include <iostream>

using namespace std;


int fibonacci(int n) {

    if (n == 0)  // Base case 1

        return 0;

    if (n == 1)  // Base case 2

        return 1;

    return fibonacci(n - 1) + fibonacci(n - 2);  // Recursive case

}


int main() {

    int terms = 10; // Example: Print first 10 Fibonacci numbers

    cout << "Fibonacci Series: ";

    for (int i = 0; i < terms; i++) {

        cout << fibonacci(i) << " ";

    }

    cout << endl;

    return 0;

}

Output:

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Explanation:

A. Base Cases:

If n == 0, return 0.

If n == 1, return 1.

B. Recursive Case:

Calls fibonacci(n-1) + fibonacci(n-2).

C. Loop in main() prints the first 10 Fibonacci numbers.

Advantages:

Several advantages of the recursion function in C++ are as follows:

  • It addresses problems like tree traversal and backtracking by simplifying code.
  • It breaks complex problems down into smaller, more manageable ones.

Disadvantages:

Several disadvantages of the recursion function in C++ are as follows:

  • It invokes more routines, which results in a higher memory usage (stack use).
  • It can cause stack overflow in the event that the depth of recursion is set excessively.

When to use Recursion:

  • When dividing a problem into smaller ones are simple.
  • When implementing an iterative solution is challenging or complex.

Conclusion:

In conclusion, recursion is a basic principle of C++, which breaks down complex problems into simpler, smaller sub-problems. It calls itself with a well-defined base case to avoid over-recursion. Despite recursion simplifying most programming cases like tree traversal, the Fibonacci series, and factorial computation, it requires careful management of memory due to the limitations of the function call stack. Recursion is neat and intuitive too, but elegance does not always come with power; sometimes, the overuse of recursion can lead to performance issues in particular cases. Iterative or optimized approaches could be better in those cases. Memoization is one possible example. Recursion is a concept that we need to master when trying to achieve clear problem-solving code through algorithms.


Related Topics

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.