Reputation: 49
my loop is only arranging the first element, i tried putting an outer loop but it is not working. do i need another loop within my program or initialize another char array[] to transfer the loop?
#include <stdio.h>
int main(void)
{
char applicants[10][15],temp[15];
char swap[10][15];
int apps,i,j,c=0;
printf("how many applicants?\n");
scanf("%d",&apps);
printf("enter the names of the applicants on seperate lines\n");
printf("in order in which they applied for > ");
for (i=0;i<apps;i++){
scanf("%s",applicants[i]);
}
printf("\napplication order\n");
printf("-----------------\n");
for (i=0;i<apps;i++){
printf("\t%s\n",applicants[i]);
}
for(i=0;i<apps-1;i++){
c=strcmp(applicants[i],applicants[i+1]);
printf("\n%d\n",c);
if(c>0)
strcpy(temp,applicants[i]);
strcpy(applicants[i],applicants[i+1]);
strcpy(applicants[i+1],temp);
}
printf("\n\n alphebatize order\n");
printf("-------------------\n");
for (i=0;i<apps;i++){
printf("\t%s\n",applicants[i]);
}
if(strcmp(applicants[0],applicants[1])>0){
printf("\n\n%s is greater than %s",applicants[0],applicants[1]);
}
}
Upvotes: 1
Views: 971
Reputation: 53006
Your if
statement lacks braces here
if(c>0)
strcpy(temp,applicants[i]);
strcpy(applicants[i],applicants[i+1]);
strcpy(applicants[i+1],temp);
this means the same as
if (c > 0)
{
strcpy(temp, applicants[i]);
}
strcpy(applicants[i], applicants[i + 1]);
strcpy(applicants[i + 1], temp);
so you are overwriting applicants[i]
with applicants[i + 1]
and then writing to applicants[i + 1]
the previous value that was stored in temp
, which is not necessarily applicants[i]
.
You need to add braces
if (c > 0)
{
strcpy(temp, applicants[i]);
strcpy(applicants[i], applicants[i + 1]);
strcpy(applicants[i + 1], temp);
}
Upvotes: 2