C++ How To Calculate the Average of an Array
Calculate the Average of an Array
Add all the elements, and divide the sum by the number of elements:
Example
int numbers[] = {10, 20, 30, 45};
int size = sizeof(numbers) / sizeof(numbers[0]);
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = static_cast<double>(sum) / size;
cout << "Average: " << average;
Explanation:sizeof(numbers) / sizeof(numbers[0]) gives the number of elements (4).static_cast<double>(sum) makes sure the decimals are kept when we divide. 105 / 4 is 26.25.