Search code examples
c++sum-of-digits

My 'cout' isn't giving correct value - why?


Simple "sum of digits" code. It compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number.

Feel free to copy and paste this into your own compiler, if you're so inclined, to see what I mean.

How can I get this to output the correct "num" value?

~~~

#include <iostream>

using namespace std;

int main()
{
  int num;
  int sum = 0;

  cout << "Please type any non-negative integer: ";
  cin >> num;

  while ( num > 0 ) {
    sum += num % 10;
    num /= 10;
  }

  cout << "The sum of the digits of " << num << " is " << sum << "\n";

  system("PAUSE");
  return 0;
}

Solution

  • You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.