Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return the sum and average of an int array?

Tags:

c#

I need to define two methods for returning the sum and average of an int array. The method defining is as follow:-

public int Sum(params int[] customerssalary)
{
           
         // I tried the following but it fails   return customerssalary.sum();
}

Another question is, how can I return the average of these int values?

like image 295
John John Avatar asked Oct 18 '12 08:10

John John


People also ask

How do you find the sum and average of an array?

Simple approach to finding the average of an array We would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean.

How do you find the average of an int array?

Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5.

How do you find the average of an int array in Java?

Example 1 to calculate the average using arrays First, create an array with values and run. the for loop to find the sum of all the elements of the array. Finally, divide the sum with the length of the array to get the average of numbers. int length = array.


2 Answers

customerssalary.Average();
customerssalary.Sum();
like image 121
L.B Avatar answered Oct 12 '22 21:10

L.B


This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!

public int Sum(params int[] customerssalary)
{
   int result = 0;

   for(int i = 0; i < customerssalary.Length; i++)
   {
      result += customerssalary[i];
   }

   return result;
}

with this Sum function, you can use this to calculate the average too...

public decimal Average(params int[] customerssalary)
{
   int sum = Sum(customerssalary);
   decimal result = (decimal)sum / customerssalary.Length;
   return result;
}

the reason for using a decimal type in the second function is because the division can easily return a non-integer result


Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.

like image 20
musefan Avatar answered Oct 12 '22 22:10

musefan