Here's my code with the sorting function implemented.
Code:
#include<stdio.h>
/*Function prototypes*/
int getdata(double[],int size);
double computesum(int n, double x[]);
double computemean(int n, double sum);
double computemedian(double x[], int n);
int main(void)
{
double x[20];
int size=0;
int n;
double sum;
n=getdata(x, 20);
computesum(n, x);
computemean(n, sum);
double median = computemedian(x, n);
}
int getdata(double x[],int size)
{
//int x[20];
//int size=0
int tmp;
int flag=0;
int n=0;
char cond, y;
while(n<size && flag == 0)
{
printf("Enter a number\n");
scanf("%d", &tmp);
printf("Are you done? Press Y if yes, otherwise press N\n");
scanf("%c", &y);
scanf("%c", &cond);
if (cond == 'n'){
flag=0;
}
else if(cond =='y')
flag=1;
x[n]=tmp;
n = n+1;
}
return(n);
}
double computesum(int n, double x[])
{
//int j;
//for (j=0; j<n; j++) printf("%f", x[j]);
int i;
double tmp;
tmp=0;
i=0;
int size;
while(i<n)
{
tmp += x[i];
i = i+1;
}
printf("Sum of the values entered is %f\n",tmp);
return(tmp);
}
double computemean(int n, double sum)
{
double mean, tmp;
mean=tmp/n;
printf("Mean of the values entered is %f\n",mean);
}
double computemedian(double x[], int n)
{
int i; /*Array elements*/
int j;
int k;
int temp; /*Temporary storage for some array element*/
double median;
printf("before sorting, the array looks like:\n");
for (j=0; j<n; j++) printf("%lf\n", x[j]);
for (j = n; j>0; j = j-1)
{
k = 0;
for (i=1; i<=j; i = i+1)
if (x[i]>x[k])
k = i;
temp = x[k];
x[k] = x[j];
x[j] = temp;
}
printf("after sorting, the array looks like:\n");
for (j=0; j<n+1; j++) printf("%lf\n", x[j]);
if (n%2 == 0)
{
median = (x[(n/2)-1] + x[(n/2)+1]) / 2;
}
else
{
median = x[n/2];
}
printf("The median of all the input values is %lf\n", median);
}
The code compiles, but for some reason, after sorting my array is getting enlarged by one digit:
This is what i get before and after sorting.
Code:
Enter a number
7
Are you done? Press Y if yes, otherwise press N
n
Enter a number
3
Are you done? Press Y if yes, otherwise press N
n
Enter a number
7
Are you done? Press Y if yes, otherwise press N
y
Sum of the values entered is 17.000000
Mean of the values entered is 5.666667
before sorting, the array looks like:
7.000000
3.000000
7.000000
after sorting, the array looks like:
0.000000
3.000000
7.000000
7.000000
The median of all the input values is 3.000000
Any idea how i can preserve the size of the array?? That 0.00000 is not supposed to be there.