find the average of all elements in an array in csharp

To find the average of all elements in an array in C#, you can use a loop to iterate through the array and add up all the element values. Then, divide the sum by the total number of elements in the array to get the average.

Here's an example code snippet that demonstrates this approach:

main.cs
int[] myArray = { 5, 3, 8, 1, 2 }; // example array
int sum = 0;

for (int i = 0; i < myArray.Length; i++)
{
    sum += myArray[i]; // add up all the element values
}

double average = (double)sum / myArray.Length; // divide the sum by the number of elements

Console.WriteLine("The average of the array is: " + average); // output the average
344 chars
12 lines

In this code, the for loop iterates through each element in the myArray array and adds its value to the sum variable. Then, the average variable is calculated by dividing the sum by the length of the array (myArray.Length). Finally, the average is output using Console.WriteLine(). Note that we cast the sum variable to a double in order to avoid integer division, which can result in truncated values for the average.

gistlibby LogSnag