+92 332 4229 857 99ProjectIdeas@Gmail.com

Sum and Average of Array Elements (C#.net)



The following code shows you how to sum up the array elements and how to average the array elements.




Code
public static void Main(string[] args)
{

    int[] arr = { 1, 2, 3, 4, 5 };
    int size = arr.Length;

    sumAverageElements(arr, size);

}

public void sumAverageElements(int[] arr, int size)
{
     int sum = 0;
     int average = 0;

     for (int i = 0; i < size; i++)
     {
          sum += arr[i];
     }
        
     average = sum / size; // sum divided by total elements in array

     Console.WriteLine("The Sum Of Array Elements Is : " + sum);
     Console.WriteLine("The Average Of Array Elements Is : " + average);
}

Output of the program is:
The Sum Of Array Elements Is : 15
The Average Of Array Elements Is : 3

0 comments: