what the point of recursion?

May 23, 2011 at 3:51pm
What is the point of recursion when all it does is weighing down the memory when large recursions are used? The reason I got this feeling was when looking at Fibonacci functions, which seem as if they can be efficiently done by using the iterative technique.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int fibo(int n)
{
	if (n <= 1)
  {return n;}
	else
   {return fibo(n-1)+fibo(n-2);}

}

int main ()
{
	for (int i = 0;i <= 10; i++)
	{
	cout << fibo(i)<<endl;
	}
	cin.get();
	return 0;
}


//This is the more efficient one for larger numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24


//iter version of fibo
//normal iter Fibo
int Fibonacci2(int nNumber)
{
int fibnum = 0, fibminus2 = 0, fibminus1 = 1;

if (nNumber == 0) return 0;
if (nNumber == 1) return 1;

for (int i=2; i <= nNumber; i++){

fibnum = fibminus1 + fibminus2;

cout << fibnum << endl;

fibminus2 = fibminus1;
fibminus1 = fibnum;

}

return fibnum;
}

May 23, 2011 at 3:57pm
Have fun writing a non recursive quicksort (I'm not saying that it's not possible though).
May 23, 2011 at 4:26pm
Recursion makes the implementation of all algorithms where "divide and conquer" can be applied much easier.
Calculating fibonacci numbers is obviously not one of these, so it would be stupid to use recursion for that.
A good example where recursion makes things easier are the Towers of Hanoi:
http://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_solution
May 23, 2011 at 4:56pm
Didn't we already have this thread? People just swap out "recursion" for "pointers/templates/classes/C++/overloading/theCommandLine" or anything else they happen to have no use for right at this second and can't imagine that anyone else ever would.

Maybe we should make a new article thread, "What's the use of xxx?" so we can just point people towards it when they ask.
Last edited on May 23, 2011 at 4:57pm
May 23, 2011 at 4:58pm
Another classic recursion: Traverse a tree of some sort (BST, a folder structure, XML/HTML parser, etc.).
May 23, 2011 at 7:12pm
These guys are right recursion has its uses. If you can't understand why now just trust us. You will find a place in code where 3 lines of recursion can handle what many lines of iteration can handle.
Topic archived. No new replies allowed.