can anyone explain the output for line e:

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 c, x = 1, y = 5;
if ((x % y) > (y % x)) cout << x; // line (a) --- output: 1
cout << endl;
for(c = x; c < y; c++) cout << c; // line (b) --- output: 1234
cout << endl;
cout << fun(-2, y) << endl; // line (c) --- output: 0
cout << y << endl; // line (d) --- output: 2
cout << fun(31459, y) << endl; // line (e) --- output: 29

how is the output for line e 29?
Last edited on
31459
3 4 9
(3 * 2 + 4) * 2 + 9
3 * 4 + 4 * 2 + 9
12 + 8 + 9
29
Add logging. See for yourself.

http://cpp.sh/723w6
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?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#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.
Im still hoping for someone to EXPLAIN in steps the outcome for line e, and not just TELL me the answer. Im trying to learn guys. Lol.
The code seems kind of idiotic. Does it do anything useful?

fun(31459, y)
        9 + 2 *  fun(314, y)
                       4 + 2 *  fun(3, y)
                                    3 + 2 * fun(0, y)
                                            0

        9 + 2       * (4 + 2     * (3 + 2 * 0)) = 29

thanks tpb, and no its not meant to do anything other than that.
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".

http://cpp.sh/723w6

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
Last edited on
Topic archived. No new replies allowed.