Program to calculate average of array in C


This program should give an insight of how to parse (read) array. We shall use a loop and sum up all values of the array. Then we shall divide the sum with the number of elements in the array, this shall produce average of all values of the array.


Let's first see what should be the step-by-step procedure of this program −

   Step 1 → Take an array A and define its values
   Step 2 → Loop for each value of A
   Step 3 → Add each element to 'sum' variable
   Step 4 → After loop finishes, divide sum with number of array elements
   Step 5 → Store that result to avg variable and display.


Let's now see the pseudocode of this algorithm −

procedure avg_array(A)

   Declare sum as integer
   FOR EACH value in A DO
      sum ← sum + A[n]
   avg ← sum / size_of_array
   Display avg

end procedure


This pseudocode can now be implemented in the C program as follows −

#include <stdio.h>

int main() {
   int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
   int sum, loop;
   float avg;

   sum = avg = 0;
   for(loop = 0; loop < 10; loop++) {
      sum = sum + array[loop];
   avg = (float)sum / loop;
   printf("Average of array values is %.2f", avg);   
   return 0;

The output should look like this −

Average of array values is 4.50