Shan Shan - 19 days ago 5
C# Question

Query regarding calculation of average of some numbers program

I am beginner in C# coding, and I am trying to write some code for the program where my program will show the average of numbers given by users. I have written below code, but I am thinking this would be more better and efficient. Can anyone please help me. Thanks in advance.

static void Main(string[] args)
{
int a=0;
double total = 0;
double result;
Console.Write("For how many numbers you want to do the average calculation: ");
a = int.Parse(Console.ReadLine());
double[] array = new double[a];
for (int j = 0; j < a; j++)
{
Console.Write("Please enter value for {0}: ", j+1);
array[j]= double.Parse(Console.ReadLine());
}
foreach (var item in array)
{
total += item;
}
result = total / a;
Console.WriteLine($"Your Calculated average value is {result}");
Console.ReadKey();
}

Answer

You dont need to take extra array for your purpose, you can do this just by adding each input value and then divide that total with total number of input items.

    double total = 0;
    double result;
    Console.Write("For how many numbers you want to do the average calculation: ");
    int a = int.Parse(Console.ReadLine());
    for (int j = 0; j < a; j++)
    {
        Console.Write("Please enter value for {0}: ", j + 1);
        total += double.Parse(Console.ReadLine());
    }

    result = total / a;
    Console.WriteLine($"Your Calculated average value is {result}");
    Console.ReadKey();
Comments