Thread: what is recursion?

1. what is recursion?

What is recursion?

For example, how can this series implemented with recursion?

a=1/2+1/3+1/4+..........1/n.

2. Well by definition its when repeated occurence. Recurrence in an equation like that would be the pattern just going on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on....... you get the picture, don't you?

3. Code:
double Divide(int num,int maxnum)
{
static double value;
if (num>=maxnum) return value;
value+=(1.0/(double)num);
Divide(num+1,maxnum);
}
Haven't tested it, but pretty sure it will do what you want.
You cannot go to infinite num in this function because of two reasons. It would be infinite loop, duh, and because your stack would overflow and crash the computer.

I think this will execute 2^n-1 times, but not positive on that.

4. >a=1/2+1/3+1/4+..........1/n.

This is a recursive relation which can be written as:

Code:
n
a =  E 1/i
i=2
So you see the recursion step can be seen from:

Code:
n-1
E 1/i + 1/n
i=2
And the end-step is i=n. This means that the function could be implemented as:

Code:
double serie (double i, double n)
{
if (i == n)
{
return 1/i;
}
else
{
return 1/i + serie (i+1, n);
}
}
Note there is an more elegant way to write this function, but that's up to you. :-)

Popular pages Recent additions