In this tutorial, we will learn and write a C++ program to find the average of numbers using an array. To understand the coding, you should have knowledge of the following topics in C++ programming:
The program takes the user input for the number of elements the user wants and the values of those elements. Based on those values, an average is calculated.
C++ Program to calculate Average of /numbers using Arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; int main() { int arrNum[200], i, n, sum = 0; float avg; cout << "Enter number of elements: "; cin >> n; // check whether n lies within 1 to 200 while (n > 200 || n <= 0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } cout << "Enter " << n << " elements" << endl; for (i = 0; i < n; i++) cin >> arrNum[i]; for (i = 0; i < n; i++) sum += arrNum[i]; avg = (float) sum / n; cout << "Average of " << n << " numbers: " << avg; return 0; } |
Output:
Enter number of elements: 4
Enter 4 elements
10
20
30
40
Average of 4 numbers: 25