C++ Program to Calculate Average of Numbers Using Arrays

To understand this example, you should have the knowledge of the following C++ programming topics:


Example: Calculate Average of Numbers Using Arrays

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

Output

Enter the numbers of data: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69

This program calculates the average of all the numbers entered by the user.

The numbers are stored in the float array num, which can store up to 100 floating-point numbers.

We first ask the user to specify how many numbers we will be calculating. This is stored in the variable n.

If the user enters a value of n above 100 or below 1, a while loop is executed which asks the user to enter a value of n until it is between 1 and 100.

while (n > 100 || n <= 0)
{
    cout << "Error! number should in range of (1 to 100)." << endl;
    cout << "Enter the number again: ";
    cin >> n;
}

Then, we use a for loop to input the numbers from the user and store them in the num array.

for(i = 0; i < n; ++i)
{
    cout << i + 1 << ". Enter number: ";
    cin >> num[i];
    sum += num[i];
}

Every time a number is entered by the user, its value is added to the sum variable.

By the end of the loop, the total sum of all the numbers is stored in sum.

After storing all the numbers, average is calculated and displayed.

average = sum / n;

Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the average of an array of numbers.

  • Return the average of all numbers in the array arr with size arrSize.
  • For example, with arr[] = {4, 6, 8, 10} and arrSize = 4, the return value should be 7.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges