1

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


}
1
  • Don't write the code so tight, it's hard for humans to read code without white spaces, you can use them to make it easier to read, the compiler will ignore them anyway. Commented Apr 20, 2015 at 15:36

1 Answer 1

2

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);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

yea i was playing around with the code a bit i must of deleted them, fixed it, okay thanks i just fixed it. added another loop within and the program ran smoothly. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.