C++ adding digits from an integer

Thread Starter

MJ320

Joined Oct 10, 2010
1
Hi,

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

DonQ

Joined May 6, 2009
321
int sumDigits(long sum = 0)
{
int result;

// blah, blah, bunch of code

return result;
}
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.
 
Top