C# program to find the 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

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.

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.

//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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.