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