thanks helios, but if you don't mind Can you explain in words on how you did it? Because I am not completely sure I understand?
Like the numbers 3 4 9 - how did you arrive at that?
#include <iostream>
int fun(int x, int &y) {
if (x < 0) y = -x;
if (x <= 0) return 0;
return x % 10 + 2 * fun(x/100, y);
}
int main() {
int y = 2;
std::cout << fun(31459, y) << '\n';
}
The line in question calls fun(31459,2). The x is clearly positive and nothing in within fun() will change its sign.
That function call returns value of 31459 % 10 + 2 * fun(31459 / 100, 2)
you have to compute the fun(31459 / 100, 2), i.e. fun(314,2) first.
That follows the same pattern. The value of fun(314,2) is 314 % 10 + 2 * fun(3, 2)
The value of fun(3,2) is 3 % 10 + 2 * fun(0,2)
The value of fun(0,2) is 0, because 0 <= 0 and the recursion won't go any deeper.
Is the extra logging not enough? It tells you exactly what values are calculated at every step. If that's not enough, this is beyond you. There is no explanation beyond "the function gets called four times, here's how the returned value is calculated each time, the last returned value is 29 as you can see".
fun called with x = 31459 , y=2
fun called with x = 314 , y=2
fun called with x = 3 , y=2
fun called with x = 0 , y=2
returning zero
returning 3 which is 3 mod ten (i.e. 3), plus two times what fun just returned
returning 10 which is 314 mod ten (i.e. 4), plus two times what fun just returned
returning 29 which is 31459 mod ten (i.e. 9), plus two times what fun just returned