Google News
logo
C++ Program to Calculate Average of Numbers Using Arrays
In the following example of C++ program to calculate the average of numbers using arrays :
Program :
#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;
    float avg;

    cout << "Enter the number of elements: ";
    cin >> n;

    int arr[n];

    cout << "Enter " << n << " integers: ";

    for(int i = 0; i < n; i++) {
        cin >> arr[i];
        sum += arr[i];
    }

    avg = (float)sum / n;

    cout << "The average is " << avg << endl;

    return 0;
}
Output :
Enter the number of elements: 5
Enter 5 integers: 21
34
15
39
54
19
The average is 28.6
This program prompts the user to enter the number of elements, creates an integer array of that size, and prompts the user to enter integers for the array.

It then calculates the sum of the integers in the array and divides by the number of elements to find the average. Finally, it prints out the average.