I need help with writing a while loop statement in c++ that works.
this is the endstate.
Total is 0
Please enter an integer: 5
Total is 5
Please enter an integer: -8
Total is 12
Please enter an integer: -13
Total is 14
Please enter an integer: -14
Total is 15
Please enter an integer: -14
You had 2 even numbers and 3 odd numbers.
This is what I have so far. I know that this is incorrect. I am new to c++ and am having difficulty grasping it. Please help. I am very frustrated with not being able to correct this. If you do help me, please, please please explain it step by step, again I am new to c++, I want to learn how to do this too.
#include <iostream>
#include <string>
using namespace std;
int main(){
int total = 0;
int num;
int even = 0;
int odd = 0;
while(total <= 30){
cout << "Total is "<< total <<endl;
cout << "Please enter an integer: ";
cin >> num;
cout <<endl;
total = total + num;
if(num%2 == 0){
even++;
}
else{
odd++;
}
}
cout << "You had " << even << "numbers and " << odd << "numbers ";
cout <<endl;
return 0;
}
sorry about not having the code tages. I will look that up. Remove which line exactly? cout <<total <<endl; or cout << "Total is " << total <<endl; ? Thank you. Corrected the way I think you were saying <fewtofie> let me know if that is what you meant. Thank you.
why are you reading in total from the user?
don't do that, its a bug I think. Remove that line.
also, welcome to the forum. Use code tage <> on the side bar for code, it makes it readable.
You have initialized the variable total to 0, and your program should basically add the input number to that total variable every time you enter one, so why you are using this line: cin >> total
that line is assigning your input to "total" overwriting its previous value.
Your code should be working fine after the removal of that line.
Also, make sure to initialize the 2 variables odd and even to 0 to avoid runtime errors.