Find The Average Of All Elements In An Array In C#
Code snippet for how to Find The Average Of All Elements In An Array In C# with sample and detail explanation
Arrays are a fantastic feature in C# that allows programmers to store multiple values in a single variable. This article offers a simple, step-by-step guide to finding the average of all elements in an array.
Code snippet for Finding the Average of All Elements in An Array
Here’s a simple C# code snippet which can be used to find the average of all the elements in an array.
public class Program
{
public static void Main(string[] args)
{
int[] numArray = new int[] {1, 2, 3, 4, 5};
double avg = Queryable.Average(numArray.AsQueryable());
Console.WriteLine("The average is: " + avg);
}
}
Code Explanation for Finding the Average of All Elements in An Array
Let’s break down the code above into smaller parts to understand better.
Step 1: First, we define a class Program
that will contain our main method:
public class Program
Step 2: We define our Main
method which is the entry point to our program:
public static void Main(string[] args)
Step 3: An integer array numArray
is declared and initialized with some values:
int[] numArray = new int[] {1, 2, 3, 4, 5};
Step 4: To find the average of the elements in the array, we use the Average
function provided by the Queryable
class. To use this function, we first have to convert our array to an IQueryable
using the AsQueryable
method.
double avg = Queryable.Average(numArray.AsQueryable());
The Average
function then returns the average of the array elements which we store in the avg
variable.
Step 5: Finally, we print the average to the console:
Console.WriteLine("The average is: " + avg);
With that, you have successfully calculated and printed the average of all elements in an array in C#.