Calculate the Average of Array Elements in C++
In this exercise, you will create a program that calculates the average of the elements in an array. This is a common task when working with arrays, especially in data analysis, where calculating averages is often required.
The goal is to sum all the elements in the array, divide the sum by the total number of elements, and return the result as the average. This exercise will help you practice working with arrays and basic mathematical operations in C++.
Logic Components
1. Accumulation
We initialize a sum variable (usually double) to accumulate the values of all elements through a loop.
2. Precision
We use the double data type for the sum and the return value to ensure the division includes decimal points.
3. Division
The average is calculated by dividing the total sum by the size of the array.
Pro Tip:
Always ensure the array size is greater than zero before dividing to avoid a division by zero error, which would crash the program.
Learning Objectives
- 1. Declare and initialize an integer array with sample data.
- 2. Create a modular function
calculateAverageto handle the logic. - 3. Practice the search pattern using conditional loops.
- 4. Output the search result clearly in the console.
Solution Implementation
#include <iostream>
using namespace std;
// Function to calculate the average of the elements in the array
double calculateAverage(int arr[], int size) {
double sum = 0; // Initialize a variable to store the sum of the elements
// Loop through the array to sum all the elements
for (int i = 0; i < size; i++) {
sum += arr[i]; // Add each element to the sum
}
return sum / size; // Return the average (sum divided by the number of elements)
}
int main() {
// Define an array of numbers
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the function to calculate the average
double average = calculateAverage(numbers, size);
// Print the result
cout << "The average of the array elements is: " << average << endl;
return 0;
}