------------------------------------------------------------------------------
MC logo
Average For Loop
[^] Code Examples
------------------------------------------------------------------------------
<<For Loops multav.cc Tom Five Times I>>
#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. 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
<<For Loops Tom Five Times I>>