Thursday, April 14, 2011

Simple recursion

Hi,

Recursion is one topic in programming which people don't really understand enough to implement in practice. It remains a very elegant programming construct, though underused.

I am writing this post because i used to think that i know recursion well enough to implement, but when i tried to explain the concept programatically i was unable to convert the theory i knew into the practical i thought i knew.

So i sat down and wrote a code to add all numbers till n, and did it using recursion.

 #include <iostream> 
using namespace std;
int addTillN(int n);
int main(int argc,char *argv[])
{
int n;
cout<<"Please enter the number till which you want the summation\t";
cin>>n;
cout<<"the summation is :\t"<<addTillN(n);
return 0;
}
int addTillN(int n)
{
static int y=0;
if(n>0)
y=n+addTillN(n-1);
return y;
}
The code above is a simple example of elegance of recursion, the other option was using plain old for loop, but isn't it just boring :)

Regards,
Ishan

No comments:

Post a Comment