Calculate the Average of a List of Numbers Using a Function

Calculate the Average of a List

This exercise helps you learn how to write a function in C++ that processes a collection of numbers and returns their average. Calculating the average is a fundamental task in statistics and data analysis, used in everything from academic grading to real-time sensor monitoring.

You will define a function that accepts an array and its size, iterates through it to calculate the total sum, and then returns the quotient of the sum and the number of elements.

Implementation Highlights

Array Handling

Learn how functions receive arrays and why passing the size separately is crucial for safe iteration in C++.

Static Casting

Using static_cast<float> ensures the division provides decimal precision instead of truncating the result.

Accumulator Pattern

Practice using loops to aggregate values from a dataset into a single sum variable efficiently.

Objective

  • 1. Define a function that receives an array and its length.
  • 2. Loop through the array to compute the total sum of elements.
  • 3. Divide the sum by the number of elements using float precision.
  • 4. Capture user input in main() and display the final average.

Example C++ Code

calculate_average.cpp Functions
#include <iostream>

using namespace std;

// Function to calculate the average of an array
float calculateAverage(int numbers[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }
    // Static cast ensures decimal precision
    return static_cast<float>(sum) / size;
}

int main() {
    int size;
    cout << "Enter the number of elements: ";
    cin >> size;

    int numbers[size];
    cout << "Enter " << size << " numbers:" << endl;
    for (int i = 0; i < size; i++) {
        cin >> numbers[i];
    }

    float average = calculateAverage(numbers, size);
    cout << "The average is: " << average << endl;

    return 0;
}

Example Output:

Enter the number of elements: 5
Enter 5 numbers: 10 20 30 40 50
The average is: 30
Related Topics
Array Logic Pointers & Arrays Casting For Loops

Share this C++ Exercise

Help others learn modular programming!

© C++ Programming Exercises. Master the art of performance coding.