Wednesday, April 22, 2009

Recursion - Basic

Recursion
An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task. To be short it is a function that calls itself. NIST-DADS states that a recursive function consists of two major parts or cases, the second part having three components.
1.base case(s), in which the problem is simple enough to be solved directly, and
2.recursive case(s). A recursive case has three components:
1.divide the problem into one or more simpler or smaller parts of the problem,
2.call the function (recursively) on each part, and
3.combine the solutions of the parts into a solution for the problem.
Depending on the problem, any of these may be trivial or complex.
To make us understand what sort of algorithm this technique is, lets have a look at the code bellow :
#include
using namespace std;
void RecursiveIncrement(int i)
{
if (i ==10) //Base case : display value of i if i == 10
{
cout << i;
}
else //Recursive case : display value of i
{
cout << i << endl;
RecursiveIncrement(++i);
}
}

int main(void)
{
RecursiveIncrement(1);
return 0;
}
The program above display integer values from 1 to 10. The base case display the value of i if its value is 10. The recursive case display the values from 1 to 9.
We have another example of such algorithm. The program work just like the previous program except that it will display the value of 10 to 1. The source code is presented below :

#include
using namespace std;

void RecursiveDecrement(int i)
{
if (i == 1)
{
cout << i;
}
else
{
cout << i << endl;
RecursiveDecrement(--i);
}
}

int main(void)
{
RecursiveDecrement(10);
return 0;
}

Those two programs are fairly simple. We are going to explore the usage of recursion to navigate several type of data list.