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.
Precision Note:
Always ensure at least one operand in your division is a floating-point type to avoid "integer division" which discards decimals.
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
#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 5 numbers: 10 20 30 40 50
The average is: 30