C++ adding digits from an integer

Discussion in 'Programmer's Corner' started by MJ320, Oct 10, 2010.

  1. MJ320

    Thread Starter New Member

    Oct 10, 2010

    I'm new to C++ and I'm trying to write a program using functions to allow the user to input an integer. The program then takes the integer and adds up the sum of the digits. I keep getting the answer showing up as 0. Any help is appreciated...

    #include <iostream>
    using namespace std;

    int extractedDigit;
    int number;
    int newNumber;
    long sum = 0;

    int sumDigits(long sum = 0)
    int result;

    if (newNumber / 10 != 0)
    extractedDigit = number % 10;
    newNumber = number / 10;
    sum += extractedDigit;
    number = sum;

    return result;

    int main()
    //Prompt user to enter an integer
    cout << "Please enter an integer: ";
    cin >> number;

    cout << "The sum of the integers in " << number << " is " << sumDigits(sum) << endl;

    system ("Pause");

    return 0;
  2. shteii01

    AAC Fanatic!

    Feb 19, 2010
    Put a bunch of cout to see what happens every step of the way. That is how I troubleshoot my programs.
  3. DonQ

    Active Member

    May 6, 2009
    Your routine never did put any value into "result". It is a function of the environment that the 'auto' variable "result" happens to contain zero. Normally, it is not guaranteed to init to any particular value and would return a random(ish) number depending on what happened to be at that location on the stack when sumDigits() was called.

    Put a value into result before sumDigits() returns.