Answer to Question #283374 in C# for kani

Question #283374

Write a program to find the median of the elements in an array. Median is the middle value in a sorted array. If there is an even number of elements in an array, then the median is mean of 2 middle values.

Sample Input and Output 1 :

Enter the number of elements in the array

5

Enter the elements in the array

2

4

1

3

5

The median of the array is 3.00


1
Expert's answer
2021-12-28T12:59:38-0500
using System;
using System.Collections.Generic;


namespace App
{


    class Program
    {
        public static void Main()
        {


            int i, j, n;


            float median, temp;


            Console.WriteLine("Enter the number of elements in the array");
            n = int.Parse(Console.ReadLine());
            float[] elements = new float[n];




            Console.WriteLine("Enter the elements in the array");
            for (i = 0; i < n; i++)
            {
                elements[i] = float.Parse(Console.ReadLine());
            }
            //sorting 
            for (i = 0; i < n - 1; i++)
            {
                for (j = 0; j < n - i - 1; j++)
                {
                    if (elements[j] < elements[j + 1])
                    {
                        temp = elements[j];
                        elements[j] = elements[j + 1];
                        elements[j + 1] = temp;
                    }
                }
            }




            //calculation median
            if (n % 2 == 0)
            {
                median = (elements[(n / 2) - 1] + elements[(n / 2)]) / 2.0F;
            }
            else
            {
                median = elements[(n / 2)];
            }






            Console.WriteLine("The median of the array is {0}", median);
            Console.ReadLine();
        }






    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS