In this tutorial, you will learn how to write a C program to calculate average using array. This is a very simple program, here you can ask user to enter array elements, then calculate the average of input numbers by dividing the sum of elements, by the number of elements.
Program to calculate average using array
In this program, user is asked to enter the number of elements, this number represents the size of array. If you want to calculate the average of 5 numbers then you should choose the array size as 5. The steps followed in this program are:
1. Ask user to enter number of elements
2. If the number of elements is less than 2 then display a message to user to enter the number again as average needs at least two elements.
3. Ask user to input all elements of array and calculate the sum of array elements.
4. Divide the sum of array elements by number of elements to get the average of input numbers.
#include <stdio.h>
int main() {
int size, i;
float num[100], sum = 0.0, avg;
printf("Enter the size of the array: ");
scanf("%d", &size);
while (size < 2) {
printf("You need at least two elements to calculate average\n");
printf("Enter the size of the array again: ");
scanf("%d", &size);
}
//Iterating the loop to store user entered numbers in the array
// and adding the each element to the variable sum to find out
// the sum of all elements of the array
for (i = 0; i < size; ++i) {
printf("Enter number %d: ", i + 1);
scanf("%f", &num[i]);
sum += num[i];
}
//average = sum of elements / number of elements
avg = sum / size;
printf("Average of array elements: %.2f", avg);
return 0;
}
Output: