Hykky Hykky - 9 days ago 5
C# Question

Generate Arrays and get only the numbers above Average

So, I'm trying to make an array that generates 20 random integers below 100, and I want to write only the numers I got from that array that are above the average, here is the code I'm using, can't proceed without knowing what I have to do now...

PS: I know my foreach is wrong, can I get some help with that too?

static void Main(string[] args)
{
int average, aboveAverage;
Random random = new Random();
for (int i = 0; i < 100; i++)
{
int[] vetor;

array = new int[20];

array[0] = random.Next(0, 100);
array[1] = random.Next(0, 100);
array[2] = random.Next(0, 100);
array[3] = random.Next(0, 100);
array[4] = random.Next(0, 100);
array[5] = random.Next(0, 100);
array[6] = random.Next(0, 100);
array[7] = random.Next(0, 100);
array[8] = random.Next(0, 100);
array[9] = random.Next(0, 100);
array[10] = random.Next(0, 100);
array[11] = random.Next(0, 100);
array[12] = random.Next(0, 100);
array[13] = random.Next(0, 100);
array[14] = random.Next(0, 100);
array[15] = random.Next(0, 100);
array[16] = random.Next(0, 100);
array[17] = random.Next(0, 100);
array[18] = random.Next(0, 100);
array[19] = random.Next(0, 100);

foreach (int elements in array)
{
average = elements / 20;
aboveAverage = ???
Console.WriteLine("{0} integers are above average.", aboveAverage);
}
Console.ReadKey();
}
}
}
}

Answer

Split it into two steps. First calculate the average. Using linq it will look like this::

var average = array.Average();

And then retrieve only those above average:

var aboveAverage = string.Join(", " array.Where(item => item > average));
Console.WriteLine($"{aboveAverage} integers are above average.");

Also you can generate all the random numbers in a nicer way using Enumerable.Repeat and .Select:

var array = Enumerable.Repeat(0, 20).Select(item => random.Next(0, 100)).ToArray();

Without linq then first iterate the collection once to sum all items so you can calculate average and then once again to find all those greater than the average:

int sum = 0;
foreach(var item in array)
{ 
    sum += item;
}
var average = sum * 1.0 / array.Length;

List<int> aboveAverageItems = new List<int>();
foreach(var item in array)
{
    if(item > average)
    {
        //If you need to know how many items and not which then use a counter and increase
        aboveAverageItems.Add(item);
    }
}

Console.WriteLine($"{string.Join(", " aboveAverageItems)} integers are above average.");
Comments