I am trying to write a simple program that asks the user to input an integer and then extracts and reprints all the digits separated by a space (ex. cin >> 12345, "1 2 3 4 5" is output), as well as displaying the sum of all the digits.
I am very close to the solution but for some reason my output displays the digits in reverse order (ex. cin >> 12345, "5 4 3 2 1" is output). I'm sure it's something very simple. I've tried looking at examples and searching for any hints, but I cannot get these digits flipped the right way! I would greatly appreciate any help that anyone could provide. Thank you!
Here is my code:
1 2 3 4 5 6 7 8 9
while (num > 0){
digit = num % 10;
cout << digit << " ";
num = num / 10;
sum = sum + digit;
}
cout << endl;
cout << sum;
You could store the digits temporarily, and then use the stored data in whichever sequence you like. You could use an array, or a vector, or maybe a stringstream as the place to store the digits..
I am just confused as to why it is outputting in reverse order when the statements are in a while loop, but not otherwise. When I take the statements out of the while loop, and have it repeat a few times to test the behavior, the characters are output sequentially. Why does a loop change that??
It's not the loop causing that, it's what you're doing in the loop.
You taking the modulo 10 of the number. That gives you the right most digit.
That's what you're displaying first. You then proceed to divide by 10 and get the second digit from the right.
Do as chervil suggested and put the digits in an array.
int showDigits(int i, bool firstCall = true)
{
if (i == 0)
return 0;
int prev = showDigits(i / 10, false);
std::cout << i % 10;
if (!firstCall)
std::cout << " + ";
return prev + (i % 10);
}
int main(void){
std::cout << "Enter an integer: ";
int number;
std::cin >> number;
int sum = showDigits(number);
std::cout << " = " << sum << '\n';
return 0;
}