C++ Program to Calculate average of n numbers using arrays


January 21, 2023, Learn eTutorial
2416

In this C++ program, we are calculating the average of n numbers, where, n is specified by the user using arrays

How to calculate the average of numbers?

Average is the arithmetic mean and is calculated by adding a group of numbers and then dividing by the count. For example, the average of 20, 30, 30, 50, 70, and 100 is 300 divided by 6, which is 50.

How to calculate the average of numbers using arrays in a C++ program?

First, the user is asked to enter a value of n. The value of n should be in the range of 1 – 100. If the value entered for n is not within the range, a while loop is executed to ask the user to enter a valid value for n. Now for a valid n, the user is asked to enter the n elements. These elements are stored in an array using a loop.

In C++, an array is a data type that can store multiple values of the same type. Here our array is float num[100]. Initially, we set a variable sum to 0. With in the for loop, every time a number is entered by the user, its value is added to the variable sum. By the end of the loop, the sum of all the n elements can be get from the variable sum. Then the average can be calculated by dividing the total sum by n.
avg = sum / n; Display the average on the screen.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare integer type variables n , i,  and float type array  num[100], sum=0.0, avg;

Step 5: Ask the user to enter the number of elements ( 1 to 100 ).

Step 6: read the number into the variable n;

Step 7: Check whether the entered value for n is in between the range 1 – 100. 

Step 8: If the condition is not satisfied then print an error message and ask the user to enter a value within the range of 1 – 100;

Step 9: Ask the user to enter the numbers.

Step 10: Read the numbers into the array num[100].

Step 11: Calculate the sum of the n numbers and store it in the variable sum.

Step 12: Compute the average by avg = sum / n;

Step 13: Display avg;

Step 14: Exit; 
 

C++ Source Code

                                          #include <iostream>
using namespace std;

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

    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];
    }

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

    return 0;
}
                                      

OUTPUT

Enter the numbers of data: 5
1. Enter number: 12
2. Enter number: 4
3. Enter number: 5
4. Enter number: 54
5. Enter number: 21
Average = 19.2