4
#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.

John Topley
  • 113,588
  • 46
  • 195
  • 237

3 Answers3

22

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) { ... }
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 2
    Really, the loop should be `while ((cin >> value) && value)` – Ben Voigt Oct 15 '18 at 16:04
  • you're right, it's the best way to avoid the infinite loop. I wasn't trying to provide the best answer loop-wise, and I'm very surprised of that much upvotes... I'll edit because your suggestion is excellent. – Jean-François Fabre Oct 15 '18 at 16:09
  • 1
    Not "iif (!value)", but "if (value == 0)". You are doing a numeric test, not a logical one! – jamesqf Oct 15 '18 at 18:26
  • well, t's a matter of taste: https://stackoverflow.com/questions/7900934/idiomatic-way-to-check-for-non-zero. here it's visible that at least 2 programmers worked on the snippet because of `if (value % 2==0)` that I would have written `if (value % 2) { odd++; } else {even++;}` – Jean-François Fabre Oct 15 '18 at 19:01
6
0 % 2 == 0

This is also counted as even 

user2397282
  • 3,798
  • 15
  • 48
  • 94
kaan bobac
  • 729
  • 4
  • 8
3

Its a good programming practice to check if you have a valid input before processing it. A similar approach here of checking the input and then decide if it needs to be processed or not (to check if it an even number or odd) should solve your problem.

As suggested in one of the answers above, checking for valid input before processing should solve your problem: if (!value) break; // stop now

Shrikanth N
  • 652
  • 3
  • 17