In: Computer Science
Write a C++ program that reads numbers from the user until the user enters a Sentinel. Use a Sentinel of -999. Ignore all negative numbers from the user input (other than the sentinel).
Do the following:
1. Output the sum of all even numbers
2. Output the sum of all odd numbers
3. Output the count of all even numbers
4. Output the count of all odd numbers
You must use alternation ('if' statements), loops and simple calculations to do this. You must not use any arrays or vectors for this program.
Ans
code:-
#include <iostream>
using namespace std;
int main()
{
int n;//to store input
cin>>n;//taking 1st input
//initialise variables for sum and count
int o=0,e=0,sume=0,sumo=0;
//while input is not -999
while(n!=(-999)){
if(n>0){//if non-negative
if(n%2==0){//if even
e++;//increment the count
sume=sume+n;//update sum
}
else{
o++;//increment the odd
sumo=sumo+n;//update the sum
}
}
cin>>n;//input from user
}//loop ends
//printing the results
cout <<"The sum of even numbers is "<<sume<<endl;
cout <<"The sum of odd numbers is "<<sumo<<endl;
cout <<"The count of even numbers is "<<e<<endl;
cout <<"The count of odd numbers is "<<o<<endl;
return 0;
}
Code:-
.
.
If any doubt ask in the comments.