About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Sort the list of Strings

Write a C program which will accept multiple strings fron the user and will sort them in ascending order.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    char *str[5],*temp;
    int i,j,n;
    printf("\nHow many names do you want to have?");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("\n Enter the name %d: ",i);
        flushall();
        gets(str[i]);
    }
    for(i=0;i<n;i++)
    {
     for(j=0;j<n-1;j++)
     {
       if(strcmp(str[j],str[j+1])>0)
         {
         strcpy(temp,str[j]);
         strcpy(str[j],str[j+1]);
         strcpy(str[j+1],temp);
         }
     }
    }
    printf("nSorted List : ");
    flushall();
    for(i=0;i<n;i++)
        puts(str[i]);
    return(0);
}

Output :

How many names do you want to have? 4
Enter the name 0: pri
Enter the name 1: prt
Enter the name 2: prq
Enter the name 3: pra


Sorted List : pra pri prq prt

Explanation :

We are checking each successive strings using strcmp() function.
if(strcmp(str[j],str[j+1])>0)
         {
         strcpy(temp,str[j]);
         strcpy(str[j],str[j+1]);
         strcpy(str[j+1],temp);
         }
If string is greater than the successive string then we are swapping the strings.

No comments: