2

I'm trying to understand why this outputs 200 because I would think that each time is adds 2+ (w-1) each time until w = 0 - wouldn't the output be much larger? Thanks!

int w = 100;
public static int mystery(int w)
{
  if (w<=0) {
  return 0;
  }
  return 2+ mystery(w-1);
}
  • 7
    Work it out on paper. Try passing in 0, 1, 2, 3... see if you can generalize the pattern. (Try running the code with those inputs, use a debugger to step through the execution to help you see if you need it). – Andy Turner Jan 15 '20 at 07:15
  • 1
    It seems you are adding 2, 100 times and same is the output. Andy is correct, use debug and check. – Vivek Jan 15 '20 at 07:19
  • See https://stackoverflow.com/q/29188074/1597897 – Franko Leon Tokalić Jan 23 '20 at 11:21

2 Answers2

6

mystery(100) calls mystery(99) which calls mystery(98), ..., which calls mystery(1), which calls mystery(0), where the recursion ends.

i.e. there are 101 calls, each of them (except of the last one, which returns 0) adds 2 to the value returned by the recursive call. A 100 times 2 equals 200.

In other words

mystery(0) returns 0
mystery(1) returns 2 + mystery(0) == 2
mystery(2) returns 2 + mystery(1) == 4
...
mystery(99) returns 2 + mystery(98) == 198
mystery(100) returns 2 + mystery(99) == 200
Eran
  • 387,369
  • 54
  • 702
  • 768
1

The recursion continues until w becomes 0.so function gets called for 101 times and adds 2 for 100 times.