Sort String Lexicographically

Program:
#include<stdio.h>
#include<string.h>
main()
{
    char s[20][20],t[20];
    int i,j,n;
    printf("Enter the number of strings:\n");
    scanf("%d",&n);
    printf("Enter the strings:\n");
    for(i=0;i<n;i++)
        scanf("%s",s[i]);
    for(i=0;i<n;i++)
        for(j=i+1;j<n;j++)
        {
            if(strcmp(s[i],s[j])>0)
            {
                strcpy(t,s[i]);
                strcpy(s[i],s[j]);
                strcpy(s[j],t);
            }
        }
    printf("\nAfter sorting:\n");
    for(i=0;i<n;i++)
        printf("%s\n",s[i]);
}

Output:
nn@linuxmint ~ $ gcc c17.c
nn@linuxmint ~ $ ./a.out
Enter the number of strings:
5
Enter the strings:
banana
apple
guava
pineapple
orange

After sorting:
apple
banana
guava
orange
pineapple
nn@linuxmint ~ $

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...