Reputation: 15
My Code needs to repeatedly prompt the user to input an integer number. When the user no longer wants to continue entering numbers, output the sum of all the positive numbers entered by the user followed by the sum of all the negative numbers entered by the user. Here is what I have so far.
#include <iostream>
using namespace std;
int main() {
int a, sumPositive, sumNegative;
string promptContinue = "\nTo continue enter Y/y\n";
string promptNum = "\nEnter a numer: ";
char response;
while (response = 'y' || 'Y') {
cout << promptNum;
cin >> a;
if(a)
sumPositive += a;
else
sumNegative += a;
cout<< promptContinue;
}
cout<< "Sum of all the positive numbers is: "<< sumPositive<<endl;
cout<< "Sum of all the negative humbers is : "<< sumNegative<<endl;
return 0;
}
Upvotes: 2
Views: 130
Reputation: 29051
Just to get this off the unanswered list:
Your while
condition is wrong
while (response = 'y' || 'Y') {
Will always evaluate to true
. This will cause an infinite loop.
It should be
while (response == 'y' || response == 'Y') {
However, this will always evaluate to false
since response
is not initialized. Fix THAT by changing this from a while...
to a do...while
loop. Also, you never retrieve a value for response
, so I'm not sure what you're expecting to happen there.
#include <iostream>
using namespace std;
int main() {
int a, sumPositive, sumNegative;
string promptContinue = "\nTo continue enter Y/y\n";
string promptNum = "\nEnter a numer: ";
char response;
do {
cout << promptNum;
cin >> a;
if(a)
sumPositive += a;
else
sumNegative += a;
cout<< promptContinue;
cin >> response;
}
while (response == 'y' || response == 'Y');
cout<< "Sum of all the positive numbers is: "<< sumPositive<<endl;
cout<< "Sum of all the negative humbers is : "<< sumNegative<<endl;
return 0;
}
There may be other bugs in this sample that I haven't yet noticed.
Upvotes: 1