How to calculate median of an array use any programming language you would like to use
The Eduladder is a community of students, teachers, and programmers just interested to make you pass any exams. So we solve previous year question papers for you.
See Our team
Wondering how we keep quality?
Got unsolved questions?

Ask Questions

Use Me  ?

New searches
Model-Question-Paper--PROGRAMMING-IN-C-AND-DATA-STRUCTURES--14PCD1314PCD23-->View question

How to calculate median of an array? Use any programming language you would like to use.

Explain

By:scribed

Taged users:
|sumesh|PerumalS|OSHO-books|neenu2|Sathish|electron|scribed|Deva|metadata|pallaviaithaln|Nisha

Likes:
Be first to like this question

Dislikes:
Be first to dislike this question
Talk about thisDelete|Like|Dislike|


Answers

If n is odd then Median (M) = value of ((n + 1)/2)th item term. Try sorting the array first. Then after it's sorted, if the array has an even amount of elements the mean of the middle two is the median, if it has a odd number, the middle element is the median

// Median and mean

#include<stdio.h>
#include<conio.h>
void main() 
{
int x[100],n,i;
float mean(int,int[]);
float median(int,int[]);
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
    scanf("%d",&x[i]);
printf("mean=%f\n",mean(n,x));
printf("median=%f\n",median(n,x));
getch();
}

float mean(int m, int a[]) {
    int sum=0, i;
    for(i=0; i<m; i++)
        sum+=a[i];
    return((float)sum/m);
}


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];
    }
}

prajwalamv

Likes:
Be first to like this answer

Dislikes:
Be first to dislike this answer
Talk about this|Once you have earned teacher badge you can edit this questionDelete|Like|Dislike|
------------------------------------

Can you help us to add better answer here? Please see this



Not the answer you're looking for? Browse other questions from this Question paper or ask your own question.

Join eduladder!