Reputation: 1
Okay I am trying to ask and sort names in C. I completed the code and it compiled without an error but I have a problem. When I input mixed characters that is Uppercase and Lowercase I get Uppercase sorted first and not in order. What should I do to my code ? Please anyone help me.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char name[30][25],temp[25];
int i,j,n;
printf("Enter how many students : ");
scanf("%d",&n);
for(i=0;i<n;i++);
{
printf("Enter the name of the student : ");
scanf("%s",name[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("The sorted names are : \n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
return(0);
}
Upvotes: 0
Views: 111
Reputation: 6707
Multiple errors:
do not end the for loop with a semicolon
for(i=0;i<n;i++);
take a second look at these variables
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
as you described you compare incorrectly for your usecase
if(strcmp(name[i],name[j])>0)
This is a possible solution:
#include <stdio.h>
#include <string.h>
char * Inputs[] =
{
"3\n",
"Carl\n",
"Frank\n",
"carl\n"
};
int in = 0;
int main()
{
char name[30][25],temp[25];
int i,j,n;
printf("Enter how many students : \n");
sscanf(Inputs[in++],"%i",&n);
printf("You entered : %i\n", n);
for(i=0;i<n;i++)
{
printf("Enter the name of the student : \n");
sscanf(Inputs[in++],"%s",&name[i]);
printf("You entered : %s\n", name[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(stricmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("The sorted names are : \n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
return(0);
}
Upvotes: 0
Reputation: 310970
First of all your program is wrong. For example instead of
scanf("%s",&name[i]);
there has to be
scanf("%s", name[i]);
Or in this statement
for(j=i+j;j<n;j++)
there is used uninitialized variable j.
As for your question then you should convert strings to upper case using standard C function toupper
declared in header <ctype.h>
Also it is better to use selection sort without copying strings every time when name[j] is less than name[i].
Upvotes: 0
Reputation: 565
You have two options. One, convert the string to lower (or upper) before comparison. Secondly strcol each string, this puts k next to K etc. Both methods are destructive so you may need to create a work string and free it after comparison.
Upvotes: 1