P.Petrov
P.Petrov

Reputation: 5

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;
}

Upvotes: 0

Views: 528

Answers (5)

Cpp Forever
Cpp Forever

Reputation: 970

You must set the tmp variable as 0
Here is your corrected code:

#include <iostream>
#include <vector>
using namespace std;
vector <int> a;
int sumDigits(int n)
{
    int tmp=0;

    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;
}

Upvotes: 0

RAM
RAM

Reputation: 2759

Your implementation of sumDigits doesn't initialize tmp if n>9, which fits exactly the case covered by your example. Therefore, tmp+=a[i] keeps on adding stuff to an integer filled with garbage.

Upvotes: 0

Eziz Durdyyev
Eziz Durdyyev

Reputation: 1158

you forgot to init sum to 0 (sum = 0;)

#include <iostream>
using namespace std;

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

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

Upvotes: 1

Shawn
Shawn

Reputation: 82

int tmp = 0;

remember that inside a function, tmp will not be initialized by default!

Upvotes: 1

john
john

Reputation: 87959

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.

Upvotes: 4

Related Questions