
Average For Loop
#include <iostream>
using namespace std;
main()
{
// Count of numbers input, total, and current input value.
int cnt, tot, num;
// Read to EOF.
for(cnt = tot = 0; cin >> num; ++cnt)
tot += num;
// Print the average.
if(cnt)
cout << "Average is " << (double)tot / (double)cnt << endl;
else
cout << "No numbers." << endl;
}
C++ iostreams facility has a number of advantages over
C stdio.
- The type of conversion is determined by the type of variable.
- There are no %d constructs, so their
number cannot disagree with the number of arguments.
- There is no need to remember to use & on input.
Note that the stdio (printf, scanf and friends) still
exist. Generally, you will not want to use them in a new C++
program. They can be useful to avoid re-writing old programs
when adding C++ code, or for using C-based libraries which
do I/O.
Reading: Ch. 8