-
Logic problem
Ok, i am busy learning recursion. I want a function that receives two int and add everyting from int a to int b. then it must return the sum
Code:
double Function(int Start, int End)
{
int sum=0;
if(End>=Start)
{
cout<<Start<<endl;
sum+=Start;
Start++;
Function(Start ,End);
}
else return sum;
}
I cant use sum because with each recursion sum gets int to zero. I dont want to pass a variable for sum to the function and i dont want to use a global variable... any suggestions for the noob?
Thanks
-
Best way:
Code:
double foo(int begin, int end, double sum = 0)
{
if (begin == end)
return sum;
sum += begin++;
return foo(begin, end, sum);
}
Otherwise you have to mess with a static or global variable and this is not recommended.
-
Ok - so without using global varibales, this is the only way? what if I dont want to pass sum to the function, but only the 2 ints? is that possible?
-
It's possible via a static variable, but then you would have trouble because you have to reset that everytime. The static variables will retain its value over the function's entire lifetime.
However, by using an optional argument as the last, you don't have to pass in a third argument when calling the function, while the function will use the third argument itself when recursing.
-
What about
Code:
double foo(int start, int end)
{
if ( end < start )
return 0;
return start + foo(start + 1, end);
}