Reputation: 171
I am currently learning to code c++ by using the web page program, where I am doing a course. Now recently I got the following exercise:
Using a while or a do-while loop, make a program that asks the user to enter numbers and keeps adding them together until the user enters the number 0.
I wrote the following code in the hope that it would bring the exercise to conclusion:
#include <iostream>
using namespace std;
int main(void){
int sum = 0;
int number;
do
{
cout <<endl;
cin >> number;
sum += number;
cout << "The total so far is: " << sum << endl;
} while (number != 0);
cout << "The total is: " << sum << endl;
}
Yet when I run the code I get the following feedback from the website (there are two links one on the left and the other on the right):
Instructions of the exercise and Webpage feedback on the exercise
Can you tell me what am I doing wrong, alternatively can you propose an alternative solution then the code I provided? Thank you for any feedback!
Upvotes: 3
Views: 865
Reputation: 310950
As for me then I would write the program the following way
#include <iostream>
int main()
{
int sum = 0;
int number;
std::cout << "Enter a sequence of numbers (0-exit): ";
while ( std::cin >> number && number != 0 ) sum += number;
std::cout << "The total is: " << sum << std::endl;
}
If you need to output partial sums then you can add one more output statement
#include <iostream>
int main()
{
int sum = 0;
int number;
std::cout << "Enter a sequence of numbers (0-exit): ";
while ( std::cin >> number && number != 0 )
{
std::cout << "The total so far is: " << ( sum += number ) << std::endl;
}
std::cout << "\nThe total is: " << sum << std::endl;
}
Upvotes: 1
Reputation: 2787
The working code is:
#include <iostream>
using namespace std;
int main(){
int sum = 0, numbers;
do{
cout << "The total so far is: " << sum << endl;
cin >> numbers;
cout<< "Number: "<< numbers;
sum += numbers;
} while (numbers != 0);
cout << "The total is: " << sum << endl;
return 0;
}
You have a mistake in the line cout>>endl;. Also, the output should match the instructions. This is why your answer was "wrong".
Upvotes: 2
Reputation: 387
I think you should design the exact same output as the instructions.
#include <iostream>
using namespace std;
int main(){
int sum = 0, numbers;
do{
cin >> numbers;
sum += numbers;
cout << "The total so far is: " << sum << endl;
} while (numbers != 0);
cout << "The total is: " << sum << endl;
return 0;
}
Upvotes: 1
Reputation: 1
You should check whether user inputs a number or a character for making sure the adding operation
Upvotes: 0
Reputation: 16476
I am guessing the website is doing a simple comparison check.
Could you remove the first cout << endl;
As that would be closer to the expected output.
As to why you are not getting the "total so far" has me stumped.
Do you see the "total so far" text when ran locally?
Upvotes: 0