Write a C++ Program to Calculate Average of Numbers Using Arrays

In this tutorial, we will learn how to calculate the average of a set of numbers using arrays in C++.

An array is a collection of elements of the same data type stored in contiguous memory locations.

Using arrays can simplify our code by providing a simple way to store and access multiple values.

To calculate the average of numbers using arrays, we can follow these steps:

  • Declare an array to store the numbers.
  • Prompt the user to enter the numbers.
  • Store the numbers in the array.
  • Calculate the sum of the numbers in the array.
  • Calculate the average by dividing the sum by the number of elements in the array.

Here is the code to implement the above steps:

#include <iostream>
using namespace std;

int main()
{
    // Declare an array to store the numbers
    int numArray[10];

    // Prompt the user to enter the numbers
    cout << "Enter 10 numbers: " << endl;

    // Store the numbers in the array
    for (int i = 0; i < 10; i++) {
        cin >> numArray[i];
    }

    // Calculate the sum of the numbers in the array
    int sum = 0;
    for (int i = 0; i < 10; i++) {
        sum += numArray[i];
    }

    // Calculate the average by dividing the sum by the number of elements in the array
    float average = (float)sum / 10;

    // Display the result
    cout << "The average of the numbers is: " << average << endl;

    return 0;
}

In the above code, we first declare an array called numArray to store the numbers.

We then prompt the user to enter the numbers and store them in the array using a for loop.

Next, we calculate the sum of the numbers using another for loop.

Finally, we calculate the average by dividing the sum by the number of elements in the array and display the result to the user.

By using arrays, we can store multiple values in a single variable and perform operations on them.

This can make our code more concise and efficient. With the above code, we can easily calculate the average of any set of numbers using arrays in C++.