• 0

Small issue in c++ program


Question

The program is a while loop and it's suppose to count how many odd and even numbers I've entered before I enter 0. My instructor provided us with to sample outputs to work with for this assignment. The first output prints out correctly, but the second doesn't.

#include<iostream>
using namespace std;

int main()
{
   int number, even = 0, odd = 0;

   cout << "Enter a non-zero integer (0 to quit): ";
   cin >> number;

   while(number != 0)
   {
   cout << "Enter a non-zero integer (0 to quit): ";
   cin >> number;

   if(number%2==0)
	  even++;
   else
	  odd++;

   }

   cout << "-----------------------------------------" << endl;
   cout << "Even Count:  " << even << endl;
   cout << "Odd Count:   " << odd << endl;
   cout << "-----------------------------------------" << endl;

   return 0;
}

The sample outputs below are the correct ones:

Sample Run 1:

Enter a non-zero integer (0 to quit): 4

Enter a non-zero integer (0 to quit): 4

Enter a non-zero integer (0 to quit): 6

Enter a non-zero integer (0 to quit): 7

Enter a non-zero integer (0 to quit): 0

-----------------------------------------

Even Count: 3

Odd Count: 1

-----------------------------------------

Sample Run 2:

Enter a non-zero integer (0 to quit): 89

Enter a non-zero integer (0 to quit): 55

Enter a non-zero integer (0 to quit): 56

Enter a non-zero integer (0 to quit): 1

Enter a non-zero integer (0 to quit): 2

Enter a non-zero integer (0 to quit): 0

-----------------------------------------

Even Count: 2

Odd Count: 3

-----------------------------------------

And here's how sample 2 prints out in my program. As you can see, it says there's 3 even numbers when there's actually 2, and it says there's 2 odd numbers when there's actually 3:

-----------------------------------------

Even Count: 3

Odd Count: 2

-----------------------------------------

Thanks!

Edited by jamesbrad288
Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0
Think about what the program is actually doing when you use cin to get 0.

Also next time you should use the

 bbcode to contain your code.

The program loops while the integer is not equal to 0. Once the integer does equal zero, it gives me an output with the number of odd and even numbers I've entered. My apologies, but I'm not sure what your asking me to do here. The code seems right to me. That's why I'm having such a hard time finding this problem.

Link to comment
Share on other sites

  • 0

As Lant says, run the code in your head, line by line: the problem is pretty obvious. If you really need a hint : the operations are correct, you're just not doing them in the right order, specifically the inputs.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.