The problem is
n is not being changed between subsequent calls to
sumDigits. Say you pass in 5,
sumDigits would go to the
else case, add 5 to the sum then it would call
sumDigits with 5 and the increased sum. Then,
sumDigits would go to the
else case, add 5 to the sum then it would call
sumDigits with 5 and the increased sum. This is an infinite loop. You need to modify
n before the next recursive call (hint: decimal point needs to be moved over by one).
if (n%100 <= 0)
This base case condition is wrong. If
n == 100, then sumDigits would (theoretically) exit and the sum would not be 1. Speaking of the base case, you're calling
sumDigits (with the same parameters) again. This leads to an infinite loop. The base case needs to simply do nothing. You can make an
if statement such that if there is at least one digit left to work with, then it does your recursive step (and then no need for an
else because the
else would be your base case that does nothing).
int sumDigits(int& n, int sum)
n shouldn't be passed by reference in this case. The print statement on the other end will be wrong.
1 2
|
return 0;
system ("Pause");
|
Here,
system("pause") is unreachable (
return 0; terminates the program). It should be placed before
return 0;. Also, there are much better ways to achieve the same effect without using
system. I don't know why it's a requirement in this assignment.
http://www.cplusplus.com/forum/beginner/1988/