Reputation: 59
Hi I am extremely new to c++. Working on an assignment where I need to add up all numbers of input then display the numbers next to eachother with the sum.
example:
input: 1234, output : 1 2 3 4 10
Here is my code so far:
#include <iostream>
using namespace std;
int main()
{
int myNum;
int total = 0;
int digit;
cout << "Enter a number" << endl;
cin >> myNum;
while(myNum >0)
{
digit =myNum %10;
myNum/=10;
total += digit;
}
while(myNum <0) {
digit =myNum %10;
myNum /=10;
total +=digit;
}
cout << "The sum of digit is:" << myNum << total << endl;
return 0;
}
The second while loop was to deal with negative numbers, but down on the cout
when I put myNum
to print the value I input it just prints 0
in front of the total, any reason the values aren't being carried over or how I could go about getting it to carry over?
Upvotes: 3
Views: 3132
Reputation: 64
No need to use a container if the sequence of digits is not required strictly in the same order.
You can simply print them as you go...
#include <iostream>
using namespace std;
int main()
{
int myNum;
int total = 0;
int digit;
cout << "Enter a number" << endl;
cin >> myNum;
cout << "The sum of digits : ";
while(myNum > 0)
{
digit =myNum %10;
myNum/=10;
total += digit;
cout << digit << " ";
}
while(myNum < 0) {
digit =myNum %10;
myNum /=10;
total +=digit;
cout << digit << " ";
}
cout << "is : " << total << endl;
return 0;
}
Upvotes: 1
Reputation: 2336
I updated the code to meet your original requirement. input:1234 output 1 2 3 4 10
The original code printed the myNum
variable after using the /= operator repeatedly. The result will always be zero.
The requirements specify that each digit of the input must be printed as well as the total. In order to save the intermediate results, a vector is introduced. As each digit is produced it is pushed into the vector.
Once the input is exhausted, the individual digits and the total can be printed. The vector is traversed in reverse to print the digits in left to right order.
using namespace std;
int main(int arg, char*argv[])
{
int myNum;
vector<int> digits;
int total = 0;
int digit;
cout << "Enter a number" << endl;
cin >> myNum;
while(myNum >0)
{
digit =myNum %10;
myNum/=10;
total += digit;
digits.push_back(digit);
}
while(myNum <0){
digit =myNum %10;
myNum /=10;
total +=digit;
digits.push_back(digit);
}
for (auto it = digits.rbegin(); it != digits.rend(); ++it)
cout << *it << " ";
cout << total << endl;
return 0;
}
Upvotes: 5