Calculate the average of an array of integers in C

To find the mean of an array, you have to go through all the cells of the array of length n, from 1 to n and memorize the sum in a variable 'sum'. At the end of the loop, we divide this sum that we have calculated by going through all the values of the array with the for loop along the length of the array.

This program allows us to browse and calculate the average of numbers of type int in the C language. You're going to notice that we did a cast float, why? Because the "average" variable is of type float, so it must be assigned to a float. You can also use and store the result of the split in a variable double.

#include< stdio.h>
#include< stdlib.h>

int main()
{
      int sum, length=10;
      medium float;
      int tab[10]={1,2,3,4,5,6,7,8,9,10};
      int   i;
      sum=0;
      for (i=0 ; i< length ; i++)
      {
          sum += tab[i];
      }
      mean = (float)sum / (float)length;
      printf("%f\n",average);
        return  0;
}


References:
Openclassrooms: Average of a table

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel ! J'ai enfin compris comment utiliser Apache POI correctement.

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

Merci Jean ! N'hésitez pas si vous avez des questions.