recursion type function in C++

As we know, the function always calls its definition. But in the recursion, the function calls itself in C++.

This type of mechanism is called Recursion in C++ and the function calls is called a Recursive function a C++.

Here is the diagram of a C++ recursion,

recursion-type-function-in-cpp

In the above diagram, the names of all three functions (function-name) will be the same.

It behaves like a loop in a way i.e. the body of function and function call are together. In recursion, the function definition calls itself again when the given condition becomes true and the function also terminates when the condition becomes false.

syntax

function_name(parameter_list) // function definition
 {
    Body of function;
    function_name(parameter_list);. // calling function
 }

Here is an example

void table(int); // function prototype
  .............
  .............

void table(int n) // function definition 
  { 
    Body of function; 
    table(n);. // recursive function
  }

Example of Recursion in C++

In this program, the function will call itself until the given condition becomes false i.e. the input (int type) given by the user becomes equal to 0 then the function will terminate.

#include<iostream>
using namespace std;
void table(int); // function declaration

int main()
 {
    clrscr();
    int num; // variable declaration
 
    cout<<"Enter a number: ";
    cin>>num;

    recursn(num); // function calling

return 0;
 }

 void table(int n) // function definition
  {
    cout<<n<<" ";
    n--;    // value decrease 1 by 1
   
    if(n!=0)            // condition check
      recursn(n); // function call itself
  }

OUTPUT

Enter a number: 5
5 4 3 2 1

Here is another example of recursion where we create a table, let’s try this

Print Table using recursion in C++

#include<iostream>
using namespace std;
void table(int,int);

int main(void)
{
   int n,i=1;

   cout<<"Enter number: ";
   cin>>n;

   table(n,i); // function calling with two argument(n,i)

return 0;
}

void table(int x,int y)
{
    for(int i=y; i<=10; i++)
        cout<<x*i<<endl;

   if(i<=10)    // recursive function call until condition false
        table(x,i);
}

OUTPUT

Enter number: 3
3
6
9
12
15
18
21
24
27
30

Explanation

in the above program table(x, i); called recursive function while this process of calling is called recursion.


Previous-function and their types in C++
Next-Pointer in C++ with examples in C+


Like it?

Leave a Reply

Your email address will not be published.