using namespace std;
int cnt = 0, // Count of numbers read.
tot = 0; // Total of numbers read.
int num; // Input number.
// Read all the numbers (until a read fails and the stream
// turns bad.)
cin >> num;
tot += num;
cin >> num;
/* Print the average. */
if(cnt > 0)
cout << "Average is " << (double)tot / (double)cnt << endl;
cout << "No numbers." << endl;
This program reads integers and adds them together as long as
there are numbers to read, then prints the average. Most of
what is shown here is familiar from Java, though we also
see some features of C++ iostreams which are not Java-like at all.
- Initially, we have several variables declared and given initial values.
- The while loop has a test and a body. It runs the test, if true
it executes the body, then repeats. Y'all probably saw that before.
- The test here asks the console reader if everything has gone okay
so far. The effect is that the loop will read integers as long as it can.
When reading fails, the loop will stop. Failure can be the end of input,
or a conversion failure. We'll run some examples. C++ does not throw
- Notice the short-cut addition operator += and the
increment operator ++.
- The if is the usual sort. A test, a true branch and a
- As in Java, multi-statement bodies must be wrapped in curly braces,
but one-statement ones need not be. It may be wiser to use the braces
in any case.