Home »
.Net »
C# Programs
C# - Find Average of Array Elements
Given an array and we have to find the average of all array elements using C# program.
Submitted by Nidhi, on August 18, 2020 [Last updated : March 19, 2023]
Here we will find the average of array elements. We will create an array of integer elements and initialized with some values and then calculate the average of all elements and print the average on the console screen.
C# program to find the average of array elements
The source code to calculate the average of array elements in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//Program to calculate the average of array elements.
using System;
class Avg
{
public static void Main()
{
int[] arr = { 1, 2, 6, 2, 18 };
int i=0;
int sum = 0;
float average = 0.0F;
for (i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
average = (float)sum / arr.Length;
Console.WriteLine("Average of Array elements: "+ average);
}
}
Output
Average of Array elements: 5.8
Press any key to continue . . .
Explanation
In the above program, we created a class Avg that contains the Main() method. In the Main() method we created an array of 5 integers initialized with some values.
for (i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
Using the above code we calculate the sum of all array elements. Here Length property of array returns the length of the array.
average = (float)sum / arr.Length;
In the above code we find the average, as we know that average may be a floating-point number then here we typecast the variable sum into float type and finally get the average and then print the average on the console screen.
C# Basic Programs »