// Program to accept integers from the keyboard until a zero is entered. Print the sum and average of the even numbers. Ignore any odd numbers in your calculations and print an appropriate message.
while (!done)
{
cout << "Enter whole numbers until average is provided: ";
cin >> number;}
if (number%2)
{
done =(number=0);
total=total +number;
average=total/number;
}
// Display results
else {}{
cout << "The sum of the positive even numbers is " << total << endl;
cout << "The average of positive even number is " << average << endl;
#include <iostream>
int main()
{
std::cout << "enter whole numbers one by one. enter zero to end input\n" ;
int cnt = 0 ; // count of even numbers
int sum = 0 ; // sum of even numbers
int number ;
// for as long as a number is entered and the number is not zero
while( std::cin >> number && number != 0 )
{
if( number%2 == 0 ) // if the number is even
{
++cnt ; // increment count
sum += number ; // add to sum
}
}
if( cnt > 0 ) // if there was at least one even number
{
std::cout << "sum of even numbers: " << sum << '\n' ;
constdouble average = double(sum) / cnt ; // avoid integer division
std::cout << "average of even numbers: " << average << '\n' ;
}
else std::cout << "there were no even numbers in the input\n" ;
}
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
void pause ()
{
string junk;
cout << "Press enter to continue... ";
cin.ignore();
getline(cin, junk);
}
int main(int argc, char ** argv)
{
///variables
int total=0;
int number;
bool done = 0;
float average;///must use float, to hold float result on it
int N = 0 ;/// # of number intered
while (1){
cout << "Enter whole numbers until average is provided: ";
cin >> number;
if (number == 0){
cout<<"0 entered\n";
break;/// goto after while
}
if (!(number % 2)){ /// intered number is even
N++;
total = total + number;
average = (float) total / N;
}else {///odd
;/// do nothings
}
cout<<"N:"<<N<<endl;
}
cout <<"after While\n";
// Display results
cout << "The sum of the even numbers is " << total << endl;
cout << "The average of even number is " << average << endl;
pause();
return 0;
}
ss@ss:~$ g++ ttt.cpp -o ttt
ss@ss:~$ ./ttt
Enter whole numbers until average is provided: 10
N:1
Enter whole numbers until average is provided: 20
N:2
Enter whole numbers until average is provided: 30
N:3
Enter whole numbers until average is provided: 0
0 entered
after While
The sum of the positive even numbers is 60
The average of positive even number is 20
Press enter to continue...
this is only care about even not positive even.
if you wish change code to be sensitive about positive numbers, simply add a condition in
if /// even section.