Average of Values
This programming challenge is from an initial C++ programming course I took in Fall 2007. The Chapter (2) was titled “Introduction to C++”.
2.5: To get the average of a series of values, you add the values up and then divide the sum by the number of values. Write a program that stores the following values in five different variables: 28, 32, 37, 24, and 33. The program should calculate the average of the numbers and display it on the screen.
My solution (using hard-coded values as per instructions):
/* Chapter 2 Challenge 5
Written by Kirk Hingsberger
September 12, 2007
Average of Values Challenge
*/
#include
using namespace std;
int main()
{
int v1 = 28;
int v2 = 32;
int v3 = 37;
int v4 = 24;
int v5 = 33;
float avg = (v1 + v2 + v3 + v4 + v5) / 5.0;
cout << "The average of the 5 values << endl;
cout << (" << v1 << ", " << v2 << ", " << v3 ", " << v4 << endl;
cout << ", and " << v5 << ") is " << avg << "." << endl;
return 0;
}
As with many other beginning C++ programs, we were instructed to not sweat the fact that our figures computed in scientific notation or with many decimal places. We would learn those controls later.
Here is the capture script I turned in for grading:
Script started on Thu 13 Sep 2007 10:13:13 AM MDT
$ cat chap2chlg5.cc
/* Chapter 2 Challenge 5
Written by Kirk Hingsberger
September 12, 2007
Average of Values Challenge
*/
#include
using namespace std;
int main()
{
int v1 = 28;
int v2 = 32;
int v3 = 37;
int v4 = 24;
int v5 = 33;
float avg = (v1 + v2 + v3 + v4 + v5) / 5.0;
cout << “The average of the 5 values << endl;
cout << (” << v1 << “, ” << v2 << “, ” << v3 “, ” << v4 << endl;
cout << “, and ” << v5 << “) is ” << avg << “.” << endl;
return 0;
}
$ g++ chap2chlg5 -o chap2chlg5..cc -s
$ chap2chlg5
The average of the 5 values
(28, 32, 37, 24,
and 33) is 30.8.
$ exit
exit
Script done on Thu 13 Sep 2007 10:13:51 AM MDT










