In this example, we have shared how to calculate average of array elements in C++ programming language. Copy and paste below code and execute it to see the program output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // How to calculate average of array elements in C++. #include <iostream> using namespace std; double average(int a[], int n) { // Find sum of array element int sum = 0; for (int i=0; i<n; i++) sum += a[i]; return sum/n; } int main() { int arr[] = {10, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << average(arr, n) << endl; return 0; } |
Program Output
1 | 6 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.