# C++ Program to Calculate Average Using Arrays

In this example, we will learn the program takes n number of element from user (where, n is specified by user), stores data in an array and calculates the average of those numbers.

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

## Example: Program to 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

##### Working

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 100, 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;`

## Next Example

We hope that this Example helped you develop better understanding of the concept of "Calculate Average Using Arrays" in C++.

**Keep Learning : )**

In the next Example, we will learn about C++ `Find Largest Element in an Array`

.