I'm trying to sort a string related to an array based on the values of the array, for some reason the sorting part inst working.. when i try to sort the elements related to each other and print them for some reason the print comes out incredibly randomly
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sorting(char name[][10],double average[],int size);
int main()
{
double sales1[10],sales2[10],sales3[10],average[10],test,totalm=0,totalfm=0,test2;
int i=0,j;
char name[10][10],gender[10];
printf("Please input the name, the gender, and the sales for the\nfirst three months followed by a spacebar after each element\n");
scanf("%s %c %lf %lf %lf",&name[0],&gender[0],&sales1[0],&sales2[0],&sales3[0]);
average[i]=(sales1[i]+sales2[i]+sales3[i])/3;
while(strcmp(name[i],"enough")!=0)
{
i++;
printf("Please input the name, the gender, and the sales for the\nfirst three months followed by a spacebar after each element\n");
scanf("%s %c %lf %lf %lf",&name[i],&gender[i],&sales1[i],&sales2[i],&sales3[i]);
average[i]=(sales1[i]+sales2[i]+sales3[i])/3;
}
sorting(name,average,i);
j=i;
while(i>=0)
{
if(gender[i]=='m')
totalm=totalm+average[i];
else
totalfm=totalfm+average[i];
i--;
}
while(j>=0)
{
test2=strcmp(name[j],"enough");
if(test2!=0)
printf("%s\t%f\n",name[j],average[j]);
j--;
}
printf("total male sales are %f\n",totalm);
printf("total female sales are %f\n",totalfm);
}
int sorting(char name[][10],double average[], int size)
{
int i=0;
double temp;
char ntemp[20][20];
while(i<=size)
{
if(average[i+1]>average[i])
{
temp=average[i];
strcpy(ntemp[i],name[i]);
average[i]=average[i+1];
strcpy(name[i],name[i+1]);
average[i+1]=temp;
strcpy(name[i+1],ntemp[i]);
}
i++;
}
}
thanks!
j=i; while(i>=0) { if(gender[i]=='m'): note last valid data index isi - 1while(i<=size) { if(average[i+1]>average[i]): out of bounds.char ntemp[20][20];? One temp varable should be enough! And why do you "know" here it is 20 but in the argument passing the first dimension is empty?