Finding the Sum of Digits Recursively

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include <iostream>

using namespace std;

int sumDigits (int x)
{
    int counter=x%10;

    if (counter==0)
    {
        return x;
    }

    else if (counter>0)
    {
        x=x/10;
        sumDigits(x);

        return sumDigits(x-1)+counter;
    }
}

int main()
{
   int num{};

   cout << "Enter a number: ";
   cin >> num;
   cout << endl;

   cout << "The sum of its digits is " << sumDigits(num) << endl;

   return 0;
}
I modified the code to this, but still experience the same issue.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

int sumDigits (int x)
{
    int counter=x%10;

    if (counter==0)
    {
        return x;
    }

    else if (counter>0)
    {
        x=x/10;
        sumDigits(x);

        return sumDigits(x-1)+counter;
    }
}

int main()
{
   int num{};

   cout << "Enter a number: ";
   cin >> num;
   cout << endl;

   cout << "The sum of its digits is " << sumDigits(num) << endl;

   return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
#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';
}

"return x == 0 ? 0 : " What does this mean?
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?
No it doesn't work. Try the number 1000. The answer should be 1.
No it does, it comes out as 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

int sumDigits (int x)
{
    if (x<10)
    {
        return x;
    }

    else if (x>9)
    {
        int counter=x%10;
        x=x/10;
        sumDigits(x);

        return sumDigits(x)+counter;
    }
}

int main()
{
   int num{};

   cout << "Enter a number: ";
   cin >> num;
   cout << endl;

   cout << "The sum of its digits is " << sumDigits(num) << endl;

   return 0;
}
You said you "removed the -1". You did a lot more than that. It's a totally different program.

BTW, the line that just says sumDigits(x) is obviously doing absolutely nothing.
Thank you, and I wrote write after the initial post the other changes I made.
Topic archived. No new replies allowed.