15,748,477 members
See more:
Im totally new to programming. Doing it about week or something. I cant find any practical help on google, yt, etc. (I found something only in Java and cant rewrite it to c#).

1) I have to ask user how many employees is working in the company.
2) User write specific salaries.
3) Program shows him average salary and salaries that are above average.

I just cant find out how to find average salary. I try plenty of variations and none of them worked.

My code looks like this:

C#
```namespace AvgSalary
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Number of employees: ");
int[] salaryArray = new int[employees];
for (int i = 0; i < employees; i++)
{
Console.WriteLine("{0}. salary of employee: ", i + 1);
}

}
}
}```

What I have tried:

int avg = salaryArray[i] / employees;
Console.WriteLine("Average salary is: {0}", avg);

And many other things. I read about .average(), but its not working.
Posted
Updated 14-Jan-20 3:03am
v2
F-ES Sitecore 14-Jan-20 5:18am
The average is the sum of all values divided by the number of values. So you have to add up every item in salaryArray then divide that sum by the number of items inside salaryArray. You can get the sum by looping through each value in the array and adding it to a "sum" variable, and the number of items is obtained from salaryArray.Length.

## Solution 1

Think about what an average is: it is the sum of all values, divided by teh number of values.
So if you have 4 values: 1, 2, 6, 7, then the average is (1 + 2 + 6 + 7) / 4, or 16 / 4 which is 4.

So you need to generate either generate a running total in your loop while the user is entering them, and divide after the loop, or add a second loop to generate the total once the entries are added.

I'd also suggest - pretty strongly - that you use `int.TryParse` instead of `int.Parse`. The latter throws an exception is the user enters anythgin that isn't a valid integer value, while the former returns a `true` / `false` value to indicate success / failure.
```for (int i = 0; i < employees; i++)
{
int value = 0;
{
Console.Writeline("Please enter a valid integer only");
}
...
}```
And we all know that everyone makes mistakes! It's pretty annoying to misskey while entering the 99th salary and have the program crash!

CPallini 14-Jan-20 5:36am
5.

## Solution 2

You can simply add the values to a `List` and then use the `Average` extension method to get the average.

C#
```List<int> salaries = new List<int> { 1, 4, 5, 2 };
double  averageSalary = salaries.Average();```

The `Average` extension method works for any `IEnumerable<int>`, so it would work with an array just as well as with a `List<int>`. :)