What is it? What is it used for? How do I use it? What's godd with it? What is not so good with it?
Printable View
What is it? What is it used for? How do I use it? What's godd with it? What is not so good with it?
Recursion is a function that calls itself. If recursion is absolutely guaranteed to be a few calls (referred to as depth of recursion)
then it has very little impact on the system.
Otherwise, as a general solution, it's a bad idea. Every recursive call pushes all of the variables and registers of the function onto the stack as they currently exist. If you call a function recursively enough you run out of stack space (memory). Basically it results in bad performance for most applications.
The other issue: a lot of recursive routines are impossible to read,
so that nobody, even yourself can work with them easily six months later.
The main use for recursion is in parser routines that use setjmp to return from parsing errors.
Ok, so recursion is nothing important for a newbie to learn?
It's not all that hard - just learn to avoid it mostly.
Ok, I got this book that asks me to write a function that gets a Fibonacci number. The function should use recursion to get the number and should look like this:If I pass it 20 it should return the twentieth Fibonacci number. How would I do this? Please explain in great detail because I find this hard to understand.Code:long fib(int n);
Fibonacci numbers are the numbers 1,2,3,5,8,13,21... To get a number you add the two before it so 1+2=3 2+3=5 3+5=8...
Ok, i'm just making this up as i go along, you would have to try it first, fix any errors (there are always some :p )
//Global variables:
long Num_A=1;
long Num_B=1;
long Num_C=0;
long fib(int n){
if (n<3)
{return Num_B;}
Num_C=Num_B;
Num_B+=Num_A;
Num_A=Num_C;
return fib(n-1);
}
Ok, this is just a possible way to do it, i'm not exactly sure if it works. Basically, you have a function that adds two number, and call this function (n-2) times. n-2 because you start with 2 numbers already.
However, this may not work, the global variable stuff may stuff up, like not having the Byval call in VB
Thank you, I'll try this when I get home