Need help with this function please

I need to create a program that lists off each digit of an integer and then display the sum off all the digits in that integer. I know that sepereatly the sum function i wrote works. But the first part which i try to list off the digits work but in reverse order which i dont know how to correct. and for some reason that i cant figure out this is affecting the sum output. Please help this is the code i have so far. Thanks.


#include <iostream>
using namespace std;

int digcount (int x) {;
int sum=0, c, dig, y=x;
while (x > 0) {
for (c=1; c<=x; c++) {
dig = x%10;
x= x/10;
cout << dig << endl;}
sum += x%10;
x= x/10;
return sum;
cout << endl;
}
}
int main () {
int x;
cout << "Enter a positive number ";
cin >> x;
if (x<=0) {return 0;}
cout << digcount (x) << endl;
return 0;
}
Please use code tags when posting code:
http://www.cplusplus.com/articles/jEywvCM9/

Do you understand how your code works? What do you think dig = x%10; does? What do you get from the original number?
Yes i know how it works. dig= x%10 gives you the last digit of the integer. i need it to go through and list each digit.
12345

The last digit is 5

1234

The last digit is 4

123

The last digit is 3

etc... do you see why it gets reversed?
so should it be dig= x/10
and then x=x%10?
im new to c++ so im a little lost. thanks
No, switching the order of the statements does not switch the order you get the digits. Instead of guessing, why not actually try it out?

There's two ways to unreverse the output. One involves appending the characters to a string and then reversing the string, or using a stack and then popping the stack, and the other way involves using log base 10 to find out how many digits there are and then looping in order.
Topic archived. No new replies allowed.