Hi there,

I am writing a program that prints the sum of even and odd numbers and here is my code

#include <iostream>

using namespace std;

const int SENTINEL = -999;

int main() {

int integers = 0;

int even = 0;

int odd = 0;

cout << "Enter an integer ending with -999: " << endl;

while (integers != SENTINEL) {

cin >> integers;

if (integers % 2 == 0) {

even = even + integers;

}

else {

odd = odd + integers;

}

}

cout << "The sum of your even integers is: " << even << endl;

cout << "The sum of your odd integers is: " << odd << endl;

return 0;

}

but now in the output it adds -999 to the odd numbers

How can I overcome this problem?

I am writing a program that prints the sum of even and odd numbers and here is my code

#include <iostream>

using namespace std;

const int SENTINEL = -999;

int main() {

int integers = 0;

int even = 0;

int odd = 0;

cout << "Enter an integer ending with -999: " << endl;

while (integers != SENTINEL) {

cin >> integers;

if (integers % 2 == 0) {

even = even + integers;

}

else {

odd = odd + integers;

}

}

cout << "The sum of your even integers is: " << even << endl;

cout << "The sum of your odd integers is: " << odd << endl;

return 0;

}

but now in the output it adds -999 to the odd numbers

How can I overcome this problem?

You could break from loop just after reading a value, if the new value is the sentinel.

#include <iostream>

using namespace std;

const int SENTINEL = -999;

int main() {

int integers;

int even = 0;

int odd = 0;

cout << "Enter an integer ending with -999: " << endl;

while ( cin >> integers && integers != SENTINEL) {

if (integers % 2 == 0) {

even = even + integers;

}

else {

odd = odd + integers;

}

}

cout << "The sum of your even integers is: " << even << endl;

cout << "The sum of your odd integers is: " << odd << endl;

return 0;

}

using namespace std;

const int SENTINEL = -999;

int main() {

int integers;

int even = 0;

int odd = 0;

cout << "Enter an integer ending with -999: " << endl;

while ( cin >> integers && integers != SENTINEL) {

if (integers % 2 == 0) {

even = even + integers;

}

else {

odd = odd + integers;

}

}

cout << "The sum of your even integers is: " << even << endl;

cout << "The sum of your odd integers is: " << odd << endl;

return 0;

}

Topic archived. No new replies allowed.