ForEach or For

I was wondering how can i cut this code down to maybe a function that could give me the average without setting the sum to be assigned to all those varibles is there a way i can loop through the values that are inputted to the console

using
System;

class Addem

{

static void Main()

{

int sum = 0;

Console.WriteLine("Enter 5 grades");

int num1 = int.Parse(Console.ReadLine());

int num2 = int.Parse(Console.ReadLine());

int num3 = int.Parse(Console.ReadLine());

int num4 = int.Parse(Console.ReadLine());

int num5 = int.Parse(Console.ReadLine());

sum = num1 + num2 + num3 + num4 + num5;

Console.WriteLine("The answer is {0}", sum.ToString());

Console.WriteLine("The average is {0}",sum/5.0);

Console.WriteLine("Press Enter to continue");

Console.ReadLine();

}

}




Answer this question

ForEach or For

  • John A. Bocharov - MSFT

    Hi Dpowers,

    You are correct. The value is cast to a double so that the average returned is accurate and includes the decimal places.

    Regards,
    Vikram

  • StLaEmpira

    Thanks for the great sample but Question....Why do you have double in the writeLine method Is that so you can return the average with double value


  • mbakhodir



    static void Main()
    {
       const int itemCount = 5;
       int sum = 0;
       
       Console
    .WriteLine("Enter {0} grades", itemCount);

       for
    (int item = 0; item < itemCount; item++)
          sum +=
    int.Parse(Console.ReadLine());

       Console
    .WriteLine("The answer is {0}", sum);
       Console.WriteLine("The average is {0}", sum / (double) itemCount);
       Console.WriteLine("Press Enter to continue");
       Console.ReadLine();
    }

     


  • ForEach or For