Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I input 3 even numbers it shows that I input 4

Tags:

c++

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

like image 633
Rendell Joseph T. Perdito Avatar asked Nov 27 '22 06:11

Rendell Joseph T. Perdito


2 Answers

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) { ... }
like image 111
Jean-François Fabre Avatar answered Dec 05 '22 10:12

Jean-François Fabre


0 % 2 == 0

This is also counted as even 

like image 39
kaan bobac Avatar answered Dec 05 '22 09:12

kaan bobac