Every time I run the program it just never prints out after I put in input. the goal is to add up every digit of a larger number and provide the exact sum, found similar but not exact questions on forums.
For example, i will enter in "123" in to the input line, then nothing happens. Just blank.
do
{
adder = user1 % 10; //does not change user1.
sum += adder; //does not change user1.
}
while (user1 != 0); //user1 still not zero? keep going until it changes... which it never will.
You've forgot to initialize the sum variable in the AddDigits function.
The do-while loop runs until user1 is zero, but user1 is never modified within the loop which means that if user1 is not zero before the loop it will run forever.
Note that the variables in main is not the same as the variables in AddDigits even if you use the same names. If you want the sum variable in main, that you have declared on line 15, to hold the value that AddDigits returns you will have to assign to it.
#include <iostream>
void AddDigits();
int main()
{
AddDigits();
return 0;
}
void AddDigits()
{
int user1;
int sum = 0;
do
{
std::cout << "Please enter an integer (0 to quit): " << std::endl;
std::cin >> user1;
sum += user1;
} while (user1 != 0);
if (user1 == 0)
{
std::cout << "The sum of the digits is " << sum << std::endl;
std::cout << "Goodbye." << std::endl;
}
}
@Peter87 i’m aware of what it does. divide and put out the remainder. it’s separating the digits for me.
Well, user1 % 10 only gives you the rightmost digit.
If user1 is 123 and you do user1 = user1 % 10; then user1 will get assigned the value 3.
Next time this code is executed user1 will again be assigned the value 3 it's still the rightmost digit.
And like that it continues forever...
What you had in your original code was almost correct. The only thing that you forgot to do was to remove the rightmost digit from user1 in each iteration of the loop. This can be done using the division operator.
Wait could i just mod the user1 then assign that to its own variable then in the do while loop after doing the mod operator and just using the division to reassign the user1 variable by 10 each time it runs through that function? until the initial digit represents a value of 0?