# Median Program In C

#### Learn Big Data Hadoop: Hands-On for Beginner

43 Lectures 1.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Learn Apache Poi

11 Lectures 2 hours

A median value is the value at the center of a sorted list. To median we need to sort the list in ascending or descending order.

For Example take the list of 3, 5, 2, 7, 3 as our input list. To find out median, first we re-order it as 2, 3, 3, 5, 7. and we find that at location 3 ((5+1)/2) is 3. So the value of median in this list is 3.

## Algorithm

Algorithm of this program is very easy −

```START
Step 1 → Take an integer list A of n values
Step 2 → Arrange the values in the list in some order, say ascending
Step 3 → Calculate the middle of list → (n + 1) / 2
Step 4 → Display the middle value as median
STOP
```

## Pseudocode

We can derive pseudocode based on the algorithm, as −

```procedure median()

Array A
Size  N
SORT(A)
middle = (N + 1) / 2
DISPLAY A[middle] as median

end procedure
```

## Implementation

Implementation of this algorithm is given below −

```#include <stdio.h>

void swap(int *p,int *q) {
int t;

t=*p;
*p=*q;
*q=t;
}

void sort(int a[],int n) {
int i,j,temp;

for(i = 0;i < n-1;i++) {
for(j = 0;j < n-i-1;j++) {
if(a[j] > a[j+1])
swap(&a[j],&a[j+1]);
}
}
}

int main() {
int a[] = {6,3,8,5,1};
int n = 5;
int sum,i;

sort(a,n);

n = (n+1) / 2 - 1;      // -1 as array indexing in C starts from 0

printf("Median = %d ", a[n]);

return 0;
}
```

## Output

Output of the program should be −

```Median = 5
```
mathematical_programs_in_c.htm