Explain recursive algorithms
I have found that the best way to understand recursion for me was to take pen and
paper and a recursion program and run through a few scenarios step by step. It's
a slow process, but it has worked well for me.
As an example, take this Fibonacci C program:
#include<stdio.h> int Fibonacci(int); main(){ int n, i = 0, c; scanf("%d",&n); printf("Fibonacci series\n"); for ( c = 1 ; c <= n ; c++ ) { printf("%d\n", Fibonacci(i)); i++; } return 0;} int Fibonacci(int n){ if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) );}source: http://www.programmingsimplified.com/c-program-generate-fibonacci-seriesIn principle, recursion is pretty simple. An initial function call is made,
and then the function keeps calling itself with different arguments unless
some break condition is met. The parent functions stay open and wait until
they get a return value from their child or children.
So, in this case, unless the argument Fibonacci() gets is zero or one, it will
take its argument, decrease it by one and two respectively, and call two child
functions with those arguments, then it will wait until it gets the return
values from those functions. The function calls which are made with zero and
one will no longer spawn child functions, but instead will return a value,
which will allow their parent to return a value, which will allow the
grandparent to return a value and so on until the initial caller gets its
return values, is able to do the final computation and then returns the value
we are actually looking for.
For a better understanding, I sincerely recommend playing this through with
pen and paper and some examples. Maybe try to map out the function calls and
the current values etc. in a tree, then you should get a pretty clear picture
of what it's about. I also tend to do this when I write more complicated
recursive code than the example above (for example, I once wrote a program
which needed to traverse the filesystem, which is another classic example for
recursion).

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now