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

Input Format:
Input consists of n+1 integers where n corresponds to the number of elements in the array.
The first integer corresponds to n and the next n integers correspond to the elements in the array. Assume that the maximum number of elements in the array is 20.


Output Format:
The output consists of a double value which corresponds to the median of the array. It is printed upto 2 digits of precision.

Refer sample input and output for formatting specifications.
[All text in bold corresponds to the input and the rest corresponds to output.]

Sample Input and Output :
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


Program Code:
#include<stdio.h>
int main() 
{
int x[100],n,i;
float median(int,int[]);
printf("Enter the number of elements in the array\n");
scanf("%d",&n);
printf("Enter the elements in the array\n");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("The median of the array is %.2f",median(n,x));
return 0;
}

float median(int n, int x[]) 
{
float temp;
int i, j;
// the following two loops sort the array x in ascending order
for(i=0; i<n-1; i++) 
{
for(j=i+1; j<n; j++) 
{
if(x[j] < x[i]) 
{
// swap elements
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
if(n%2==0) 
{
// if there is an even number of elements, return mean of the two elements in the middle
return((x[n/2] + x[n/2 - 1]) / 2.0);
else 
{
// else return the element in the middle
return x[n/2];
}
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: