Hey everyone,
I'm trying to practice strings and I need you're help.
I tried to build a code by myself where i'm sorting my strings in lexicographic order but i had to peak at the solution .
I have a few questions to ask because i really need to master that subject.
so first here's the code:
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char names[100][50], temp[100][100];
int num,i,j = 0;
int k = 0;
printf("Enter number of names: ");
scanf("%d", &num);
printf("Enter names:\n");
for (i=0; i<num; i++)
{
scanf("%s", names[i]);
}
for (i=0; i<num; i++)
{
for (j=0; j<num-1; j++)
{
if (strcmp(names[j], names[j+1])>0)
{
strcpy(temp[k], names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp[k]);
}
}
}
for (i=0; i<num; i++)
{
printf("%s", names[i]);
}
}
So here are my questions:
1- on the for loops where i make my calculation of the strings. What does j represent?
Correct me if i'm wrong:
num = 3 (for example) and I'm inputting 'yann' so j[0] = yann, j[1] = ann j[2] = nn and j[3] = n ??
2- why on the second for loop i have to declare j<num-1?
3- can someone explain to me the if statement? what does strcmp(names[j], names[j+1]) mean? and why does it have to be >0??
4- please explain to me the rest of the if statement.