This recursive function is intended to sum a numbers digits, but it always returns the expected answer-the amount of digits. So for example, If i enter 567, it will return 15 (18-3), if I enter 56, it will return 9 (11-2), if I enter 998, it will return 23, (26-3).
#include <iostream>
int sumDigits(int x) {
return x == 0 ? 0 : sumDigits(x / 10) + x % 10;
}
int main() {
int num = 0;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "The sum of its digits is " << sumDigits(num) << '\n';
}
I removed the "-1" from the return call "sumDigits(x-1)+counter", and it worked. Though I am confused why the -1 is not necessary, could somebody please clarify this for me?