I need to write a program that prompts the user to input a number of integers, then displays how many even numbers (including zeros) and how many odd numbers there are. Then the program needs to display the sum of the even numbers and the sum of the odd numbers. I've got the first half done, but I can't figure out how to display the sums. Here is what I've got:
#include <iostream>
#include <iomanip>
usingnamespace std;
constint N = 10;
int main()
{
int counter;
int number;
int zeros = 0;
int odds = 0;
int evens = 0;
int exit;
cout << "Please enter " << N << " integers. They can be positive, negative, or zero." << endl;
for (counter = 1; counter <= N; counter++)
{
cin >> number;
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1:
odds++;
}
}
cout << endl;
cout << "There are " << evens << " even numbers, which includes " << zeros << " zeros." << endl;
cout << "The sum of the even numbers is " << SUMEVEN << endl;
cout << " " << endl;
cout << "There are " << odds << " odd numbers." << endl;
cout << "The sum of the odd numbers is " << SUMODD << endl;
cout << " " << endl;
cout << "Type 'exit' to exit." << endl;
cin >> exit;
}
I put SUMEVEN where I am going to put the sum of the even numbers and SUMODD for the sum of the odd numbers. How do I do this?
#include <iostream>
#include <iomanip>
usingnamespace std;
constint N = 10;
int main()
{
int counter;
int number;
int zeros = 0;
int odds = 0;
int evens = 0;
int sumEven = 0;
int sumOdd = 0;
int exit;
cout << "Please enter " << N << " integers. They can be positive, negative, or zero." << endl;
for (counter = 1; counter <= N; counter++)
{
cin >> number;
switch (number & 1)
{
case 0:
evens++;
if (number == 0)
zeros++;
//sumEven = 0; <<- DELETE THIS
sumEven = sumEven + number;
break;
case 1:
case -1:
odds++;
// sumOdd = 0; <-- DELETE THIS
sumOdd = sumOdd + number;
}
}
cout << endl;
cout << "There are " << evens << " even numbers, which includes " << zeros << " zeros." << endl;
cout << "The sum of the even numbers is " << sumEven << endl;
cout << " " << endl;
cout << "There are " << odds << " odd numbers." << endl;
cout << "The sum of the odd numbers is " << sumOdd << endl;
cout << " " << endl;
cout << "Type 'exit' to exit." << endl;
cin >> exit;
}
number %2 and number&1 , gives the same result. You can choose one of them.As far as i remember number&1 works faster in general, because it's a bitwise operation.