C++ Program to Calculate Average of Numbers Using Arrays

Updated on February 24, 2025
Calculate average of numbers using arrays header image

Introduction

Calculating averages is a fundamental operation in many programming and data analysis tasks. In C++, you might often find situations where you need to compute the average of a series of numbers stored in an array. This operation exemplifies how you can manipulate arrays and perform arithmetic computations efficiently.

In this article, you will learn how to calculate average in C++ and how to compute the average of numbers using arrays. Through detailed examples, discover the application of loops for iteration and the use of basic arithmetic operations to solve this common programming task.

Program to Calculate Average in C++

cpp
#include <iostream>
  using namespace std;
  int main() {
      int n;
      cout << "Enter the number of elements: ";
      cin >> n;
      double numbers[n], sum = 0.0, average;
      cout << "Enter " << n << " numbers: ";
      for (int i = 0; i < n; i++) {
          cin >> numbers[i];
          sum += numbers[i]; // Add each number to sum
      }
      average = sum / n; // Calculate average
      cout << "The average is: " << average << endl;
      return 0;
  }

Calculating Average Using a Static Array

Define and Initialize the Array

  1. Start by declaring and initializing an array with predefined values.

  2. Calculate the total number of elements in the array.

  3. Initialize a variable to store the sum of array elements.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        int numbers[] = {8, 4, 6, 9, 5};
        int length = sizeof(numbers) / sizeof(numbers[0]);
        int sum = 0;
    

    The array numbers is declared with five integer elements. The length variable holds the count of these elements, crucial for looping through the array.

Sum the Elements of the Array

  1. Loop through each element in the array using a for loop.

  2. Add each element to the sum variable.

    cpp
    for(int i = 0; i < length; i++) {
        sum += numbers[i];
    }
    

    This loop iterates over each element in the array, accumulating the values into sum.

Calculate and Display the Average

  1. Declare a variable to store the average.

  2. Calculate the average by dividing the sum by the number of elements.

  3. Output the average.

    cpp
    double average = double(sum) / length;
    cout << "Average is: " << average << endl;
    return 0;
    }
    

    The average is calculated by converting the sum to a double for precision during division. The average is then printed to the console.

Calculating Average Using a Dynamic Array

Dynamically Allocate Array and Input Values

  1. Prompt the user for the number of elements.

  2. Dynamically allocate an array of that size.

  3. Loop through the array to input values from the user.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cout << "Enter number of elements: ";
        cin >> n;
        int *numbers = new int[n];
        int sum = 0;
    
        for(int i = 0; i < n; i++) {
            cout << "Enter number " << i + 1 << ": ";
            cin >> numbers[i];
        }
    

    This code segment dynamically allocates an array based on user input for flexible array sizes.

Calculate Sum and Average

  1. Sum the elements input by the user.

  2. Calculate the average.

  3. Display the average and release the allocated memory.

    cpp
    for(int i = 0; i < n; i++) {
        sum += numbers[i];
    }
    double average = double(sum) / n;
    cout << "Average is: " << average << endl;
    delete[] numbers;
    return 0;
    }
    

    After summing the elements, the average is calculated similar to the static array example. Memory is freed using delete[] to avoid memory leaks.

Program with an Average Function in C++

You can create a function in C++ to calculate the average of an array of numbers. Here's an example:

calculateAverage() Function:

  1. Takes an array and its size as arguments.
  2. Loops through the array to calculate the sum.
  3. Returns the sum divided by the size (i.e., the average).

main() Function:

  1. Accepts user input for the number of elements.

  2. Stores numbers in an array.

  3. Calls calculateAverage() and prints the result.

    cpp
    #include <iostream>
     using namespace std;
     double calculateAverage(double arr[], int size) {
         double sum = 0.0;
         for (int i = 0; i < size; i++) {
             sum += arr[i]; // Add each element to sum
         }
         return sum / size; // Return the average
     }
     int main() {
         int n;
         cout << "Enter the number of elements: ";
         cin >> n;
         double numbers[n]; 
         cout << "Enter " << n << " numbers: ";
         for (int i = 0; i < n; i++) {
             cin >> numbers[i]; 
         }
         double avg = calculateAverage(numbers, n);
         cout << "The average is: " << avg << endl;
    
         return 0;
     }
    

Program to Calculate the Average of 5 Numbers in C++

  1. Declare an array numbers[5] to store the five numbers.

  2. Use a loop to take user input and calculate the sum.

  3. the sum by 5 to compute the average.

  4. Display the average using cout.

    cpp
    #include <iostream>
     using namespace std;
    
     int main() {
         double numbers[5], sum = 0.0, average;
    
         cout << "Enter 5 numbers: ";
         for (int i = 0; i < 5; i++) {
             cin >> numbers[i];  // Input numbers
             sum += numbers[i];  // Add each number to sum
         }
    
         average = sum / 5;  // Calculate average
    
         cout << "The average is: " << average << endl;
    
         return 0;
     }
    

Conclusion

Calculating the average of numbers using arrays in C++ is an excellent way to familiarize yourself with array operations, iteration structures, and basic memory management with dynamic arrays. By mastering these examples, you enhance your ability to handle fundamental data manipulation tasks in C++. Whether using static or dynamic arrays, the principles of calculating averages remain consistent and are essential for many future programming scenarios.