Friday, October 30, 2009

Chap9[F]b Arrange words alphabetically

Write a program to sort a set of names stored in an array in alphabetical order.

void main()
{
char words[10][20];
char temp[30];
char temp2[30];
char clear[1]={'\0'};

int i,j;

for(i=0;i<10;i++)
{
printf("\nKey in the %d) word",i+1);
scanf("%s",&words[i][0]);
}

for(i=0;i<9;i++)
{
for(j=0;words[i][j]!=0;j++)
{
if(words[i][j]>words[i+1][j])
{
strcpy(temp,&words[i][0]);
strcpy(temp2,&words[i+1][0]);
strcpy(&words[i][0],clear);
strcpy(&words[i+1][0],clear);
strcpy(&words[i][0],temp2);
strcpy(&words[i+1][0],temp);

i=-1;
}

else if (words[i][j]==words[i+1][j])
continue;

else
break;

}
}

for(i=0;i<10;i++)
{

printf("\n%s",&words[i][0]);
}
}

Note: This code only works for small letters.
If you want to use uppercase letters then create a function to convert all uppercase to lowercase first then do the main code then at the end convert back to uppercase and print.

1 comment:

  1. strcpy(&words[i][0],clear);
    strcpy(&words[i+1][0],clear);

    why these 2 lines are there for, its working good without it....

    ReplyDelete