In this article, We will see two programs to find the average of numbers using array. First Program finds the average of specified array elements. The second programs takes the value of n (number of elements) and the numbers provided by user and finds the average of them using array.
Example 1: Program to find the average of numbers using array
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
static void Main() { double sum=0, avg=0; double[] numbers = { 10, 20, 50, 40}; for(int i=0;i<numbers.Length;i++) { sum += numbers[i]; } avg = sum / numbers.Length; Console.WriteLine("The Sum is : "+sum); Console.WriteLine("The Average is : "+avg); Console.ReadKey(); } |
Output:
Example 2: Calculate average of numbers entered by user
In this example, we are using Scanner to get the value of n and all the numbers from user.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
static void Main() { double sum=0, avg=0; Console.Write("How many numbers you want to enter?"); int n = Int32.Parse(Console.ReadLine()); double[] numbers = new double[n]; for(int i=0;i<numbers.Length;i++) { Console.Write("Number {0}: ", i + 1); numbers[i] = Convert.ToDouble(Console.ReadLine()); sum += numbers[i]; } avg = sum / numbers.Length; Console.WriteLine("The Sum is : "+sum); Console.WriteLine("The Average is : "+avg); Console.ReadKey(); } |
Output:
Wow!!!!!!!!!!!!!!! Thank you so much for this.
It really rescued me with my assignment, you are the best. I will always come to this website!