To calculate the median from given array, First, you have to sort the given array either in ascending OR descending order. If the number of elements is even number, then the average of two numbers in the middle will be the median.
If the number of elements is the odd number, then the middle element of the array after sorting will be considered as the median.
In the below example, we have added 5 elements of the array.
1 2 3 4 5 6 7 8 9 | Input Array: Elements are: 35,54,31,22,85 Sorted array is: 22,31,35,54,85 Median is: The median is : 35.000000 |
Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include <stdio.h> void Array_sort(int *array , int n) { // declare some local variables int i=0 , j=0 , temp=0; for(i=0 ; i<n ; i++) { for(j=0 ; j<n-1 ; j++) { if(array[j]>array[j+1]) { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } printf("\nThe array after sorting is..\n"); for(i=0 ; i<n ; i++) { printf("\narray_1[%d] : %d",i,array[i]); } } float Find_median(int array[] , int n) { float median=0; if(n%2 == 0) median = (array[(n-1)/2] + array[n/2])/2.0; else median = array[n/2]; return median; } int main() { int array_1[30] = {0}; int i=0 ,n=0; float median=0; printf("\nEnter the number of elements for the array : "); scanf("%d",&n); printf("\nEnter the elements for array_1..\n"); for(i=0 ; i<n ; i++) { printf("array_1[%d] : ",i); scanf("%d",&array_1[i]); } Array_sort(array_1 , n); median = Find_median(array_1 , n); printf("\n\nThe median is : %f\n",median); return 0; } |
Enter the number of elements for the array : 5
Enter the elements for array_1..
array_1[0] : 35
array_1[1] : 54
array_1[2] : 31
array_1[3] : 22
array_1[4] : 85
The array after sorting is..
array_1[0] : 22
array_1[1] : 31
array_1[2] : 35
array_1[3] : 54
array_1[4] : 85
The median is : 35.000000
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.