Group
Arrays and Vectors in C++
Objective
1. Define an array with several integer values.
2. Create a function that takes the array and its size as input.
3. Inside the function, sum all the elements of the array.
4. Divide the sum by the size of the array to calculate the average.
5. Return the calculated average.
6. Test the program with different arrays.
Implement a function that calculates the average of the elements of an array.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// 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; // End of program
}
Output
The average of the array elements is: 30