MASIGNASUKAv102
6510051498749449419

C++ Recursion - Learn With AVRK

Add Comments
Thursday, September 2, 2021

Recursion in C++ Language

Recursion refers to a situation where the same function is called within the function itself. The function which calls the same function is known as recursive function.

A function that calls itself, and does not perform any tasks after the function call, is known as tail recursion. In tail recursion, we usually call the same function with a return statement.

Let's look at a simple example of recursion -
recursion()
{
    recursion(); /*calling self function*/
}


C++ Recursion Example -

Let's look at an example to print the factorial of a number using recursion in C++ language.
#include <iostream>
using namespace std;
void change(int data);
int main()
{
    int factorial(int);
    int fact,value;
    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); /*Wrong value*/
    if(n==0)
    return(1); /*Terminating condition*/
    else
    {
        return(n*factorial(n-1));
    }

}


Output -

Enter any number : 6
Factorial of a number is : 720

We can understand the above program of recursive method from the figure given below -

Loading...

Also check out this : C++ Functions - Learn With AVRK
Learn With AVRK

Learn With AVRK