How to compute Average for the Set of Values using C#?

CsharpProgrammingServer Side Programming

Firstly, set an array with values −

int[] myArr = new int[] {
   34,
   23,
   77,
   67
};

To get the average, firstly get the sum of array elements.

Divide the sum with the length of the array and that will give you the average of the elements −

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

The following is the complete code to get the array in C# −

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      int[] myArr = new int[] {
         34,
         23,
         77,
         67
      };
      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("Average = " + average);
   }
}

Output

Average = 50
raja
Updated on 22-Jun-2020 13:13:36

Advertisements