Search code examples
c++sumdigits

Function, which outputs the sum of the digits of an integer in C++?


I have written a function that ought to print the sum of all digits of a given integer. However the program outputs incorrect result, it should output 19. I want to ask why this happens? The program outputs 2686935.

#include <iostream>
#include <vector>
using namespace std;
vector <int> a;
int sumDigits(int n)
{
    int tmp;
    if((n>1 && n<9) || n==1 || n==9)
    {
        tmp=n;
        return tmp;
    }
    while(n>9)
    {

        a.push_back(n%10);
        n/=10;
        if((n>1 && n<9) || n==1 || n==9)
        {
            a.push_back(n);
        }
    }
    for(int i=0; i<a.size(); i++)
    {

        tmp+=a[i];

    }
    return tmp;
}
int main()
{
    cout<<sumDigits(12745);
    return 0;
}

Solution

  • It's way too complex. This should work (except for negative numbers)

    int sumDigits(int n)
    {
        int total = 0;
        while (n > 0)
        {
            total += n%10;
            n /= 10;
        }
        return total;
    }
    

    Combination of n%10 and n/10 in a loop gives you each digit in the number, then just add them up.

    The error in your original code is that tmp is not initialised to zero.