#include <iostream>
using namespace std;
int main(){
int odd=0, even=0, value;
cout<<"Enter Numbers\n";
cout<<"Enter 0 to End\n";
do{
cin>>value;
if (value % 2==0)
even++;
else
odd++;
}
while (value !=0);
cout<<"The number of odd numbers is: "<<odd<<endl;
cout<<"The number of even numbers is: "<<even;
return 0;
}
Something is wrong and I need help, when I end the program there is always +1 in even numbers.
the problem is that when you enter 0 to end the loop it counts it as an even number before exiting the loop...
Break as soon as 0 is entered instead, and use an infinite loop
for (;;)
{
cin>>value;
if (!value) break; // stop now
if (value % 2==0)
even++;
else
odd++;
}
as stated in comments, an alternative would be to use a conditional while
loop which short-circuits if the input fails & tests the value against zero. in that case, you don't need to test for zero within the loop:
while ((cin >> value) && value) { ... }
0 % 2 == 0
This is also counted as even
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With