#include <stdio.h>
float average(float a[]); // Function prototype
int main() {
float avg, c[] = {23.4, 55, 22.6, 3, 40.5, 18}; // Array of ages
avg = average(c); // Pass the array to the average function
printf("Average age = %.2f", avg); // Print the average
return 0;
}
float average(float a[]) {
int i;
float avg, sum = 0.0; // Initialize sum to 0.0
for (i = 0; i < 6; ++i) { // Loop through each element of the array
sum += a[i]; // Add each age to the sum
}
avg = (sum / 6); // Calculate the average
return avg; // Return the average
}
Header File Inclusion
#include <stdio.h>
This line includes the standard input-output library, which is necessary for using the
printf
functionFunction Prototype
float average(float a[]);
This line declares the
average
function, indicating that it will take an array of floats as an argument and return a float value.Main Function
int main() { float avg, c[] = {23.4, 55, 22.6, 3, 40.5, 18}; avg = average(c); printf("Average age = %.2f", avg); return 0; }
- An array
c
is declared and initialized with six float values representing ages. - The
average
function is called with the arrayc
passed as an argument. In C, when you pass an array to a function, you actually pass a pointer to its first element. - The returned average is stored in the variable
avg
. - Finally, the average is printed to the console using
printf
.
- An array
Average Function
float average(float a[]) { int i; float avg, sum = 0.0; for (i = 0; i < 6; ++i) { sum += a[i]; } avg = (sum / 6); return avg; }
- The function initializes a variable
sum
to 0.0 to accumulate the total of the ages. - A
for
loop iterates through the array, summing each age tosum
. - After the loop, the average is calculated by dividing
sum
by the number of elements (6). - The calculated average is returned to the caller.
- The function initializes a variable
Output
When the program runs, it computes the average of the ages in the array c
and outputs the result formatted to two decimal places. The expected output would be:
Average age = 27.90