UncleCoder.com

UncleCoder.com

Free programming examples and instructions

# C program to Sort a given set of strings

## C program to Sort a given set of strings

Posted on 11 Sep 2017 Category: C Views: 396

Edited on 27 Sep 2017

# In the last article, we have seen that how to sort a given set of integers. Now we will see how to sort and display a given set of strings.

This C program also explains two C library functions namely ‘strcmp’ and ‘strcpy’.

strcmp () is a C library function which can be used to compare two strings and returns zero if two strings are equal.

``strcmp(string1,string2);``

strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.

strcpy() which copies the contents of source string to the destination string. The syntax is given as follows

``strcpy(stringdestintion, stringsource);``

The program reads input from the user and final output is sorted set of strings. The C program for the same is given as below

``````#include <stdio.h>
#include <conio.h>
#include <string.h>
/* string.h header file supports all string functions.*/
void main()
{
char name[50][50];
char temp[50];
int i,n,j;
printf(“enter the array size :”);
scanf(“%d”,&n);
printf(“\nenter the array elements :”);
flushall();
for(i=0;i<n;i++)
{
gets(name[i]);   //read input string from the user
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf(“\n\tsorted array elements :\n”);
for(i=0;i<n;i++)
{
puts(name[i]);  //prints the string
}
getch();
}
``````

In this program flushall() is used to clear the buffer.

output

• View all

• View all

• View all