Program : Compute the average of elements in a 1-D array in C++.
Solution :
#include <iostream> using namespace std; int main() { const int size = 5; int arr[size],i,sum; float avg; cout << "Enter " << size << " elements of an array :\n"; for (i = 0; i < size; i++) { cin >> arr[i]; } for (int i = 0; i < size; i++) { sum += arr[i]; } avg = sum / size; cout << "Average of array elements: " << avg; return 0; }
Output :
Enter 5 elements of an array: 1 2 3 4 5 Average of array elements: 3.0
Dry Run :
i | i<size | arr[i] | sum=sum+arr[i] | i++ |
0 | True | arr[0]=1 | = 0 + 1 => 1 | 1 |
1 | True | arr[1]=2 | = 1 + 2 => 3 | 2 |
2 | True | arr[2]=3 | = 3 + 3 => 6 | 3 |
3 | True | arr[3]=4 | = 6 + 4 => 10 | 4 |
4 | True | arr[4]=5 | = 10 + 5 => 15 | 5 |
5 | False | —————- | ————– | —————— |
So, it calculates the sum of all the elements as 15 and then computes the average by dividing the sum by the size of the array. The result, in this case, is 3.0.
Want to practice more problems involving Array 1-D ? Click here.