- Write a C++ program to Calculate Average Of Array Elements.

In this program we will learn about taking integer input from user and storing it in array. Then we will find the sum of all array elements using for loop and finally calculate the average of N input numbers stored in an array.

**Algorithm to find average of N numbers stored in an array**

Let inputArray is an integer array having N elements.

- Declare an integer variable 'sum' and initialize it to 0. We will use 'sum' variable to store sum of elements of array.
- Using for loop, we will traverse inputArray from array index 0 to N-1.
- For any index i (0<= i <= N-1), add the value of element at index i to sum. sum = sum + inputArray[i];
- After termination of for loop, sum will contain the sum of all array elements.
- Now calculate average = sum/N;

## C++ program to find average of numbers using arrays

#include <iostream> using namespace std; int main() { int i, count, sum, inputArray[500]; float average; cout << "Enter number of elements\n"; cin >> count; cout << "Enter " << count << " elements\n"; // Read "count" elements from user for(i = 0; i < count; i++) { cin >> inputArray[i]; } sum = 0; // Find sum of all array elements for(i = 0; i < count; i++) { sum += inputArray[i]; } average = (float)sum / count; cout << "Average = " << average; return 0; }Output

Enter number of elements 5 Enter 5 elements 3 4 5 6 7 Average = 5

Enter number of elements 6 Enter 6 elements 2 4 6 8 10 12 Average = 7

In above program, we first take number of elements as input from user and store it in variable count. Using a for loop, we take count numbers as input from user and store in an integer array inputArray. Then using a for loop, we find the sum of all array elements and store the result in sum variable. Finally, to find the average of all array elements we divide sum by count.

**Recommended Posts**