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?
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.
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.
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.
customerssalary.Average();
customerssalary.Sum();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With