C# Tutorial
This C# program is used to find the median value from the set of array elements using for loops.
Number of floating elements is also the user input and need to provide list of floating array elements.
Reads n array floating elements and finds the median value and displaying it.
/* This C# program to find and display median value. Also added single and multiline comments. */ using System; // System is a namespace public class Median { // Main method which starts the program execution. public static void Main() { int i, j, n, max; float median, temp; Console.Write("Enter number of elements:"); n = int.Parse(Console.ReadLine()); float[] a = new float[max]; /* Reading array elements */ Console.WriteLine("Input " + n + " values"); for (i = 0; i &t; n; i++) { a[i] = float.Parse(Console.ReadLine()); } temp = 0; /* sorting */ for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (a[j] < a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } /* calculation median */ if (n % 2 == 0) { median = (a[(n / 2) - 1] + a[(n / 2)]) / 2.0F; } else { median = a[(n / 2)]; } /*printing result */ for (i = 0; i < n; i++) Console.WriteLine(a[i] + "\t"); Console.WriteLine("Median is " + median); Console.ReadKey(); } }
Output:
C:> csc Median.cs C:> Median Enter number of elements:5 Input 5 values 25 32 11 42 78 78 42 32 25 11 Median is 32
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page