finding average of elements in array using struct in C?
Code to find average of elements in array using struct in C
#include <stdio.h>
struct Array {
int arr[5];
};
float findAverage(struct Array a) {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += a.arr[i];
}
return (float)sum / 5;
}
int main() {
struct Array myArray = {{1, 2, 3, 4, 5}};
float avg = findAverage(myArray);
printf("Average of array elements: %.2f", avg);
return 0;
}
Explanation:
- We define a struct named
Array
with an arrayarr
of size 5 to hold the elements. - The function
findAverage
takes a struct of typeArray
as an argument and calculates the average of the elements in the array. - Inside the
findAverage
function, we initialize a variablesum
to 0 to store the sum of the elements in the array. - We use a for loop to iterate through the array and calculate the sum of its elements.
- We return the average of the elements by dividing the sum by the total number of elements in the array, casting the result to a float to obtain a decimal value.
- In the
main
function, we create an instance ofArray
namedmyArray
and initialize it with values {1, 2, 3, 4, 5}. - We then call the
findAverage
function, passingmyArray
as an argument, and store the result in the variableavg
. - Finally, we print the average of the array elements using
printf
.