Q:

C# program to find the average of array elements

belongs to collection: C# Basic Programs | array programs

0

C# program to find the average of array elements

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to convert a two-dimensional array into... >>
<< C# program to make a simple ATM machine...