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.
Program:
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.
Output:
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.
Using the above code we calculate the sum of all array elements. Here Length property of array returns the length of the array.
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.