How to find the average of elements of an integer array in C#?


The following is our integer array −

int[] myArr = new int[6] {
   8,
   4,
   2,
   5,
   9,
   14
};

Firstly, get the length of the array, and loop through the array to find the sum of the elements. After that, divide it with the length.

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

Here is the complete code

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      int[] myArr = new int[6] {
         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);
   }
}

Output

Sum = 42
Average Of integer elements = 7

Updated on: 22-Jun-2020

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements