C++ Code Example: Average of Array

The main function is the starting point of the program. An integer variable quantity and an integer variable i are declared. An array of floating-point numbers numbers with 20 elements and a floating-point variable result are also declared.

The next part of the code outputs a prompt to the user asking for the number of elements to store in the numbers array and stores the user’s input in the quantity variable.

The first for loop iterates quantity times and stores the user’s input in each element of the numbers array.

This second for loop iterates over the numbers array and adds up the elements in the array. The average of the array is then calculated by dividing the sum of the elements by the number of elements.

Finally, the average of the elements in the numbers array is output to the user and the program returns 0, indicating a successful completion.

#include <iostream>
using namespace std;

int main () {
    int quantity, i;
    float numbers[20], result;

    cout << "How many numbers do you want to store in array? (1 - 20) " << endl;
    cin >> quantity;

    // Store numbers in array (user input)
    for(i = 0 ; i < quantity ; i++) {
        cout << "Please enter a number: " << endl;
        cin >> numbers[i];
    }
    
    // Loop over array and sum up the array entries
    for(int i = 0; i < quantity; i++) {
        result += numbers[i];
    }

    result = result / quantity;

    cout << "Average of array is: " << result << endl;

    return 0;
}
Output
How many numbers do you want to store in array? (1 - 20) 
5
Please enter a number: 
54
Please enter a number: 
22
Please enter a number: 
89
Please enter a number: 
33
Please enter a number: 
12
Average of array is: 42