1

I'm attempting to create a method that will calculate the sum of a an integer, as the integer is broken down in to single integers.

E.g. 2546 becomes 2, 5, 4, 6. Then I plus those all together.

2 + 5 + 4 + 6 = 17

The method will run recursively.

I'd made this program non-recursively, but in that one, I had a variable to store a sum of the calculation.

public static int calcSum(int n){
    if (n>0)
    return ((n%10) + calcSum(n/10)); 
    else
        return 0; 
 }

The program works, I just don't understand how the sum is stored.

1 Answers1

2

The sum is not stored in any variable (unless the caller of the recursive method will store the result in some variable).

The recursive method returns the sum to its caller without storing it in a variable:

return ((n%10) + calcSum(n/10)); 

or returns 0 if the input is 0.

calcSum(2546) returns 6 + calcSum(254)
calcSum(254) returns 4 + calcSum(25)
calcSum(25) returns 5 + calcSum(2) 
calcSum(2) returns 2 + calcSum(0)
calSum(0) returns 0

so when the recursion unwinds:

calcSum(2) returns 2 + 0 == 2
calcSum(25) returns 5 + 2 == 7
calcSum(254) returns 4 + 7 == 11

and finally

calcSum(2546) returns 6 + 11 == 17
Eran
  • 387,369
  • 54
  • 702
  • 768