Notan Deward - 1 year ago 47

C++ Question

Hello Everyone i am new to C++ Programming a College Freshmen.

(this not a homework or project, he just give me some task to do)

i was given a task to write and run a program that reads a sequence of integers until a negative integer is entered, then prints the sum of the positive even and positive odd integers. Use a While Loop.

Basically the user have infinite amount to enter integers and it will only stop if he entered a negative integers and it will display all the number of Even and Odd.

i try my best to do it by myself without asking for help in the internet but this what i got. i am still new to programming and i'm looking forward for you help. better if you can complete it and i will study out the codes.

`#include <iostream>`

using namespace std;

int main()

{

int n;

int odds =0;

int evens =0;

cout<<"Enter Positive integers. \n\t:";

cin>>n;

while (n>0)

{

switch(n%2)

{

case 0:

evens++;

break;

case 1:

odds++;

}

}

cout<<endl;

cout<<"the number of odds: "<<odds<<endl;

cout<<"the number of evens: "<<evens<<endl;

}

Answer Source

This is what you need:

```
int main()
{
int n;
int odds = 0;
int evens = 0;
while(cin >> n) {
if(n < 0) {
break;
}
else {
if((n % 2) == 0) {
++odds;
}
else {
++evens;
}
}
}
cout << "the number of odds: "<< odds << endl;
cout << "the number of evens: "<< evens << endl;
}
```

I wrote this code as simple as possible so you can understand what is going on. The `while(cin >> n)`

keeps reading values(it will terminate if an `EOF`

flag is set). Then the program checks if the number is negative and exits the for loop, otherwise it calculates if the number is `odd`

or `even`

. You can experiment with this code by adding switch statements instead of ifs.