In this C++ tutorial, you shall learn how to write a program to find the average of elements in the given integer array.

C++ Find Average of Elements in Integer Array

To find the average of elements in an integer array, loop through the elements of this array using a For Loop or While Loop, accumulate the sum in a variable, and then divide the sum with the number of elements in array.

Examples

1. Find average of integers in the array {2, 4, 6, 8}

In the following example, we take an integer array initialized with some elements, and find the average of the elements of this array.

main.cpp

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int x[] = {2, 4, 6, 8}; //integer array
    int len = sizeof(x) / sizeof(x[0]); //get array length
    int sum = 0; //initialize sum with 0
    float avg = 0; //initialize average with 0
    
    for (int i = 0; i < len; i++) {
        sum += x[i]; //accumulate sum
    }
    
    avg = sum / len;
    
    cout << "Average : " << avg << endl;
}

Output

Average : 5
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the average of elements of an integer array, with the help of example C++ programs.