Recursion is the process of a function calling itself. A function that calls itself is called a recursive function.
When a function calls itself within its own body and does not perform any tasks after the function call, it is called tail recursion. In tail recursion, the same function is typically called using a return statement.
Let’s look at a simple example of recursion:
void recursionfunction() { recursionfunction(); // Call the function itself }
👇Click to receive👇
👉C Language Knowledge Resource Collection
C++ Recursion Example
Let’s look at an example that uses recursion to print the factorial in C++.
#include<iostream> using namespace std;
int factorial(int);
int main() { int value, fact; cout << "Enter any number: "; cin >> value; fact = factorial(value); cout << "Factorial of a number is: " << fact << endl; return 0;}
int factorial(int n) { if (n < 0) return (-1); /* Invalid value */ if (n == 0) return (1); /* Termination condition */ else { return (n * factorial(n - 1)); }
Output:
Enter any number: 5Factorial of a number is: 120

Recommended
-
C Language Tutorial – Answers to Common C Language Interview Questions (3)
-
CLion Tutorial – IDE Script Console Control in CLion
-
C++ Tutorial – Detailed Explanation of Pass by Value and Pass by Reference in C++