Group
Functions in C++
Objective
1. Define a function that receives an array of numbers and its length.
2. Loop through the array to compute the total sum of the elements.
3. Divide the total sum by the number of elements to get the average.
4. In the main function, ask the user for the number of elements and then input each number into an array.
5. Call the function and display the average result.
Write a function that calculates the average of a list of numbers.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Function to calculate the average of an array of numbers
float calculateAverage(int numbers[], int size) {
int sum = 0; // Variable to store the total sum
// Loop through each element in the array
for (int i = 0; i < size; i++) {
sum += numbers[i]; // Add each element to the sum
}
// Calculate and return the average
return static_cast<float>(sum) / size;
}
// Main function - entry point of the program
int main() {
int size; // Variable to store the number of elements
// Ask the user for the number of elements
cout << "Enter the number of elements: ";
cin >> size; // Read the size
int numbers[size]; // Declare the array with the given size
// Prompt the user to input the numbers
cout << "Enter " << size << " numbers:" << endl;
for (int i = 0; i < size; i++) {
cin >> numbers[i]; // Read each number
}
// Call the function to calculate the average
float average = calculateAverage(numbers, size);
// Display the calculated average
cout << "The average is: " << average << endl;
return 0; // End of the program
}
Output
Enter the number of elements: 5
Enter 5 numbers:
10
20
30
40
50
The average is: 30