How to find the Average Values of all the Array Elements in C#?


To find the average values, firstly set an arrayL

int[] myArr = new int[10] {
   45,
   23,
   55,
   15,
   8,
   4,
   2,
   5,
   9,
   14
};

Now find the sum and divide it by the length of the array to get the average.

int len = myArr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < len; i++) {
   sum += myArr[i];
   average = sum / len;
}

Let us see the complete code −

Example

using System;
public class Program {
   public static void Main() {
      int[] myArr = new int[10] {
         45,
         23,
         55,
         15,
         8,
         4,
         2,
         5,
         9,
         14
      };
      int len = myArr.Length;
      int sum = 0;
      int average = 0;
      for (int i = 0; i < len; i++) {
         sum += myArr[i];
      }
      average = sum / len;
      Console.WriteLine("Sum = " + sum);
      Console.WriteLine("Average Of integer elements = " + average);
   }
}

Updated on: 22-Jun-2020

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements