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:
In 20 years of programming I have never used and never seen a recursive function....until a few days ago. A program was core dumping and my heart sank when I looked at the code and saw, horror of horrors, a recursive function. Have you ever tried to debug one? Recursive functions are for display only and should never be used in the real world. They are a nightmare.
ReplyDeleteYeah really, recursive functions are a bit difficult when it comes to debugging but sometimes problems are better solved using it.
ReplyDeleteOne more thing, there are peoples who themselves think recursively and they find it easier to implement things using recursive functions. Much like you I don't!