C++ Program to calculate Average of Numbers using Arrays

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

#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