C Program to Calculate Average Using Arrays

This post shows how to calculate the average of all the values in the array using C programming language.

C Program to Calculate Average Using Arrays

#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;
    //calculation process
    for(loop=0;loop<10;loop++) 
    {
      sum=sum+array[loop];
    }
   avg=(float)sum/loop;
   //to display result
   printf("Average of array values is %%.2f", avg);   
   return 0;
}

Output

Explanation

We start the program by initializing the array value and the variables, where the sum and loop operate the integer values and average holds the float value. 

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

Now we start the calculation part, where we use for condition to do the calculation and to get the average(avg) value.

	//calculation process
    for(loop=0;loop<10;loop++) 
    {
      sum=sum+array[loop];
    }
   	avg=(float)sum/loop;

After the calculation, we proceed further to get the result and we use %.2f to stop after two decimal points.

//to display result
   printf("Average of array values is %%.2f", avg);   
   return 0;

We now get the desired result.