Skip to content

Instantly share code, notes, and snippets.

@mhmd-azeez
Last active May 24, 2016 13:34
Show Gist options
  • Select an option

  • Save mhmd-azeez/21da4f550375587bdd32150c262254d8 to your computer and use it in GitHub Desktop.

Select an option

Save mhmd-azeez/21da4f550375587bdd32150c262254d8 to your computer and use it in GitHub Desktop.
Second course practical exam, C++
/*
* Practical Examination second semester
* Group (B)
* Write a program that asks the user to input (8) numbers (using loop while)
* Then the program should:
* 1. Find the average of the even numbers.
* 2. Display 'the average is even' message on the screen, if the average is even.
*/
‪#‎include‬ <iostream>
using namespace std;
void main()
{
int average = 0; // average of the even numbers
int numEvens = 0; // number of the even numbers
int sum = 0; // sum of the even numbers
int i = 0; // used by the while loop
while (i++ < 8) // <== notice the i++
{
// get a number from the user and put it in 'thisNumber'
int thisNumber;
cout << "Give me a number: ";
cin >> thisNumber;
// if the number that the user gave us was even,
// then add it to sum and add one to numEvens
if (thisNumber % 2 == 0)
{
sum += thisNumber;
numEvens++;
}
}
// if there were no even numbers (if all the numbers were odd),
// then it should exit the program. if we don't exit the program,
// then at line 53: (average = sum / numEvens) would be
// (average = 0 / 0) which is undefined. so the program might crash.
// ئەگەر بەکارهێنەرەکە هیچ ژمارەیەکی جووتمان نەداتێ، دەبێ لە
// بەرنامەکە بچێتە دەرەوە، ئەگەر وانەکەین لە هێڵی ٥٣ کە نووسراوە
// average = sum / numEvens
// هەڵە ڕوودەدا لەبەر ئەوەی ئەڤێرەیج یەکسان دەبێت بە سفر دابەش سفر
// کە ئەویش پێناسە نەکراوە. بۆیە بەرنامەکە تێکدەشکێت.
if (numEvens <= 0)
{
cout << "You did not give me any even number \n";
system("pause");
return; // exit the program
}
// average of even numbers = the sum of even numbers / the number of even numbers
average = sum / numEvens;
cout << "Average: " << average << endl;
if (average % 2 == 0)
cout << "Average is even.\n";
system("pause");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment