VOOZH about

URL: https://www.geeksforgeeks.org/cpp/types-of-recursion-in-cpp/

⇱ Types of Recursion in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Types of Recursion in C++

Last Updated : 23 Jul, 2025

Recursion is a process where a function calls itself, either directly or indirectly to repeat the same task for smaller data. In C++, recursion occurs by writing a function that includes a call to itself within its body.

Based on how and where this function calls are present, recursion in C++ can be classified into the following types:

πŸ‘ Types-of-Recursion

Let’s look at each type one by one.

1. Direct Recursion

Direct recursion occurs when a function calls itself directly from within its body. This is the most common and straightforward form of recursion.

Example:


Output
5 4 3 2 1 

In this example, the show() function calls itself directly with a reduced value of n.

Direct recursion can be divided into:

A. Head Recursion

In head recursion, the recursive call happens before any processing in the function. The function calls itself first and processes later.


Output
0 1 2 3 4 5 

Here, the function goes deep into recursion first and processes while returning.

πŸ‘ head_recursion_in_c

B. Tail Recursion

In tail recursion, the function processes first and the recursive call is the last operation.


Output
5 4 3 2 1 

Tail recursion can be more memory-efficient and may benefit from compiler optimizations.

πŸ‘ tail_recursion_in_c

C. Tree Recursion

Tree recursion happens when a function calls itself more than once within its body, forming a tree-like structure.


Output
3 2 1 1 2 1 1 

The function calls itself twice for each value, branching like a tree.

πŸ‘ Lightbox

D. Nested Recursion

Nested recursion means the argument to a function is itself a recursive call.


Output
91

This type of recursion is complex and used only when necessary.

2. Indirect Recursion

In indirect recursion, a function does not call itself directly. Instead, it calls another function that eventually calls the first one, creating a chain of calls.


Output
10 9 4 3 1 

Here, funcA() calls funcB(), which calls funcA() again, forming indirect recursion.

πŸ‘ indirect_recursion_in_c
Comment
Article Tags:
Article Tags: