C Tutorial

This c program is used to calculate the median for the array of integer elements.

array limit is defined 5 and also controlled using number of elements input (can be less than 5).

Sorting the array elements by descending order and computes the median value from the sorted array elements.

#include<stdio.h> #define N 5 void main() { int i, j, n; float median, a[N], temp; printf("Enter number of elements:\n"); scanf("%d", &n); /* Reading array elements */ printf("Input %d values \n", n); for(i=0; i<n; i++) { scanf("%f", &a[i]); } 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.0; else median = a[(n/2)]; /*printing result */ for(i=0; i<n; i++) printf("%f\t", a[i]); printf("\nMedian is %f\n", median); }Output:

$ cc median.c $ ./a.out Enter number of elements: 5 Input 5 values 2 4 3 1 5 5.000000 4.000000 3.000000 2.000000 1.000000 Median is 3.000000

C Program Examples

C Tutorial

Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page

^