Program To Calculate Average In C


Advertisements

An average of set of numbers is their sum divided by their quantity. It can be defined as −

average = sum of all values / number of values

Here we shall learn how to programmatically calculate average.

Algorithm

Algorithm of this program is very easy −

START
   Step 1 → Collect integer values in an array A of size N
   Step 2 → Add all values of A
   Step 3 → Divide the output of Step 2 with N
   Step 4 → Display the output of Step 3 as average
STOP

Pseudocode

Lets write pseudocode for the driven algorithm −

procedure average()
   
   Array A
   Size  N
   FOR EACH value i of A
      sum ← sum + A[i]
   END FOR
   average = sum / N
   DISPLAY average
   
end procedure

Implementation

Implementation of this algorithm is given below −

#include <stdio.h>

int main() {
   int i,total;
   int a[] = {0,6,9,2,7};
   int n = 5;

   total = 0;
   
   for(i = 0; i < n; i++) {
      total += a[i];
   }

   printf("Average = %f\n", total/(float)n);
   return 0;
}

Output

Output of the program should be −

Average = 4.800000
mathematical_programs_in_c.htm
Advertisements