Introduction to Recursive Functions

Recursion is a process of defining something in terms of itself. Function recursion
therefore means to define a function in terms of itself, in other words a function
that calls itself inside its body is known as recursive functions.


Example:


   void func (something)
{
something…
something…

func(something);
}

Notice how the function func () is calling itself!


Why use recursive Functions?


In most cases recursive functions can be replaced by iterative statements,
then why use recursive functions?


Here are a few points that justify its use:




  • Recursive functions make the code easier and simpler to understand.




  • There are certain algorithms that could be very easily implemented using
    recursion but are pretty much difficult to implement using iterative or
    other non-recursive methods.




  • Some of the people tend to think recursively, so their thoughts can be
    better implemented using recursion.




Below is a simple example program to illustrate recursion. We have included
both the recursive and non-recursive version of the same function so that it
would be easy for you to understand the similarities and differences between
the two.


  // -- Recursive Functions --
// Example program to illustrate
// recursion
// NOTE: factorial is the product
// of whole numbers between 1 and
// n (argument)
#include<iostream.h>

// function prototypes
int factorial_simple(int);
int factorial_recursive(int);

void main(void)
{
cout<<"Calling simple function\n";
cout<<factorial_simple(3);
cout<<endl;

cout<<"Calling recursive function\n";
cout<<factorial_recursive(3);
cout<<endl;
}

int factorial_simple(int n)
{
int result=1,i;

// doing by iteration
for(i=1;i<=n;i++)
result*=i;

return result;
}

int factorial_recursive(int n)
{
int result;

if(n==1) return 1;

// calling itself
result=factorial_recursive(n-1) * n;

return result;
}

Please note that a conditional statement is necessary inside a recursive function
to force the function to return without recursion. Failing to do so will make
the function never to return.


Hope this helps!


Related Articles:


Check out this stream