------------------------------------------------------------------------------
MC logo
For Loop Average
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Counted Average Example] [For Loop Average] [For Loops] [Read-To-End Average] [Reading In the While Test] [Counting Example 1] [Counting Example 2] [Counting Example 3] [Counting Example 4] [Counting Example 5] [Watch Out For This] [Switch] [Switch Using Break] [Break and Continue] [Change Adder]
multav0f.cpp
#include <iostream>
using namespace std;

main()
{
        // Find out how many numbers to read.
        int how_many;           // The expected number of inputs.
        cout << "How many numbers you want to enter? ";
        cin >> how_many;

        // Numbers until we reach the count.
        int tot = 0;            // Total of numbers read.
        for(int i = 1; i <= how_many; ++i) {
                // Read a number.
                int num;
                cin >> num;

                // Update stats.
                tot += num;
        }

        // Print the average.
        if(how_many > 0)
                cout << "Average is " 
                     << (double)tot / (double)how_many << endl;
        else
                cout << "No numbers." << endl;
}

This is a version of the last one which uses a for loop instead of a while. It also uses the increment and shortcut operators instead of boring old add.