What is recursion?
For example, how can this series implemented with recursion?
a=1/2+1/3+1/4+..........1/n.
What is recursion?
For example, how can this series implemented with recursion?
a=1/2+1/3+1/4+..........1/n.
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?
Haven't tested it, but pretty sure it will do what you want.Code:double Divide(int num,int maxnum) { static double value; if (num>=maxnum) return value; value+=(1.0/(double)num); Divide(num+1,maxnum); }
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.
>a=1/2+1/3+1/4+..........1/n.
This is a recursive relation which can be written as:
So you see the recursion step can be seen from:Code:n a = E 1/i i=2
And the end-step is i=n. This means that the function could be implemented as:Code:n-1 E 1/i + 1/n i=2
Note there is an more elegant way to write this function, but that's up to you. :-)Code:double serie (double i, double n) { if (i == n) { return 1/i; } else { return 1/i + serie (i+1, n); } }