Array Average
Program to calculate average of array elements
BeginnerTopic: Array Programs
C++ Array Average Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
double sum = 0;
cout << "Enter number of elements: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
sum += arr[i];
}
double average = sum / n;
cout << fixed << setprecision(2);
cout << "Average of array elements: " << average << endl;
return 0;
}Output
Enter number of elements: 5 Enter 5 elements: 10 20 30 40 50 Average of array elements: 30.00
Understanding Array Average
To calculate average, we sum all array elements and divide by the number of elements. We use double for sum and average to handle decimal results. The setprecision(2) formats the output to 2 decimal places.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.