Average an array whose size is determined by the user at run time, accumulating the values in an array. - CSharp Language Basics

CSharp examples for Language Basics:Array

Description

Average an array whose size is determined by the user at run time, accumulating the values in an array.

Demo Code

using System;//from  w w  w.  j av a  2  s  . co  m
public class Program
{
   public static void Main(string[] args)
   {
      Console.Write("Enter the number of values to average: ");
      string numElementsInput = Console.ReadLine();
      int numElements = Convert.ToInt32(numElementsInput);
      double[] doublesArray = new double[numElements];
      for (int i = 0; i < numElements; i++)
      {
         Console.Write("enter double #" + (i + 1) + ": ");
         string val = Console.ReadLine();
         double value = Convert.ToDouble(val);
         doublesArray[i] = value;
      }
      double sum = 0;
      for (int i = 0; i < numElements; i++)
      {
         sum = sum + doublesArray[i];
      }
      double average = sum / numElements;
      Console.Write(average + " is the average of (" + doublesArray[0]);
      for (int i = 1; i < numElements; i++)
      {
         Console.Write(" + " + doublesArray[i]);
      }
      Console.WriteLine(") / " + numElements);
   }
}

Result


Related Tutorials