OneBite.Dev - Coding blog in a bite size

find the average of all elements in an array in C

Code snippet on how to find the average of all elements in an array in C

int main() 
{ 
  int arr[100],sum=0,n;
  printf("Enter number of elements in array\n");
  scanf("%d", &n);
  printf("Enter elements of array\n");
  for (int i=0; i<n; i++)
  {
    scanf("%d", &arr[i]);
    sum += arr[i];
  }
  int avg = sum/n;
  printf("Average of the elements in array = %d", avg);
  return 0;
}

This code finds the average of all the elements in an array. The array size is declared as 100, the sum of the elements is stored in a variable called “sum”, the number of elements in the array is stored in the variable “n”. The array is printed and the sum is calculated by adding all the elements in the array one by one, each element is added to a variable called “sum” and stored in an array called “arr”. Finally the average of the elements is calculated by dividing the sum of the elements by the number of elements. The average is stored in the variable “avg” and printed to the user.

c