0

Sum of all the natural numbers up to n.

Adding n before recursive call gives out 15 and adding it after the recursive call shows 10.

public static int SumThem(int n){
    if(n==0){
        return n;
    }
    return SumThem(--n) + n;
}

public static void main(String[] args){
    int x = SumThem(5);
    System.out.println(x);
}

Output: 10.

The output is 10 which means, while returning, the value for n=5 is not evaluated in the return statement. It only works up to n=4, but as soon as the n is added before the recursive call it works fine.

public static int SumThem(int n){
    if(n==0){
        return n;
    }
    return n + SumThem(--n);
}

public static void main(String[] args){
    int x = SumThem(5);
    System.out.println(x);
}

Output: 15

n=5 does count here. Why is this happening?

Abra
  • 19,142
  • 7
  • 29
  • 41
  • 2
    Ask yourself why you are using a modifying operator on `n` in the first place. Then think about what order the evaluation happens in – UnholySheep Sep 05 '22 at 08:34

1 Answers1

1

Your problem is that you are changing the value of [method parameter] n inside method SumThem. I can rewrite method SumThem as follows:

public static int SumThem(int n) {
    if (n == 0) {
        return n;
    }
    --n;
    int tmp = SumThem(n);
    return tmp + n;
}

The above code is the same as your code, it just does each operation in a separate statement, for example:

SumThem(--n) + n;

First n is decremented. Then method SumThem is called. Then the value returned by method SumThem is added to n.

Initially the value of n is 5, so the above code first changes the value of n to 4. Then it calls SumThem(4) – which returns 6. Then 6 is added to n (which is now 4 since you decremented it before recursively calling SumThem). Hence the result is 10 (ten).

What you need to do is not change the value of n. So your method needs to be:

public static int SumThem(int n) {
    if (n == 0) {
        return n;
    }
    return SumThem(n - 1) + n;
}
Abra
  • 19,142
  • 7
  • 29
  • 41