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
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?
double Function(int Start, int End)
else return sum;
Otherwise you have to mess with a static or global variable and this is not recommended.
double foo(int begin, int end, double sum = 0)
if (begin == end)
sum += begin++;
return foo(begin, end, sum);
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.
double foo(int start, int end)
if ( end < start )
return start + foo(start + 1, end);