Using Arrays to Calculate Average of Numbers in C++

Exercise:

Write a C++ program that can calculate the average of numbers using arrays.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int Tnum;
    float num[100], sum=0.0, avg;
    cout << "Insert the number of data entries (1-100): ";
    cin >> Tnum;
    while (Tnum > 100 || Tnum <= 0)
    {         
        cout << "Error! The number is not in the range of (1-100)" << endl;
        cout << "Insert the number again: ";
        cin >> Tnum;
    }
    for(int x = 0; x < Tnum; ++x)
    {         
        cout << x + 1<<".  ";
        cin >> num[x];
        sum += num[x];
    }
    avg = sum / Tnum;
    cout << "\nThe total average is: " << avg;
    return 0;
}
Click Here to View the Output:
Insert the number of data entries (1-100): 5
43.43
355.3
322.4
21
78.533 
The total average is: 164.133
Click Here to View the Explanation:
  • This program requires the user to enter numbers and finds the average of all numbers with the help of arrays.
  • float num [100] is added in the code which allows the code to save as much as 100 floating-point numbers.
  • The user is asked to specify the amount of numbers that will be involved in the calculation Tnum.
  • The number is entered by the user and while loop is used to ensure that the value of Tnum entered is not above 100. If it is, the user is asked to re-enter a number Insert the number again.
  • As the numbers are entered, they are stored in the sum variable. The numbers are added and when the loop is terminated, sum is divided by Tnum.
  • This displays the average of the numbers.