C Program to print strings in alphabetical order

C Program to print strings in alphabetical order

2013
6
SHARE

C Program to print in alphabetical order or Lexicographical order : As we all know there are several ways to sort strings alphabetically but using arrays is the easiest.  Ordering Strings into alphabetical form is also referred as Lexicographical ordering of strings. Today we will learn how to sort or print strings in alphabetical order using .  Actually its quite easy stuff, simply apply the bubble sort algorithm on strings i.e. compare two adjacent strings and swap strings accordingly based on order you want.

Simple Logic of Sorting Strings in Alphabetical Order or Lexicographical order is below :

for (i=0;i<m;i++)
for (j=i+1;j<m+1;j++)
{
if (strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}

Now let us see how to write a .

C program to Print Strings in Alphabetical Order :

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
char a[50][50],temp[100];
int i,j,m,n;
printf("Enter the number of elements you wish to order : ");
scanf("%d",&m);
printf("\nEnter the names :\n");
for (i=0;i<m+1;i++)
gets(a[i]);
for (i=0;i<m;i++)
for (j=i+1;j<m+1;j++)
{
if (strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
printf("\n\nSorted strings are : ");
for (i=0;i<m+1;i++)
puts (a[i]);
getch();
}

 Output of the Program :

Enter the number of elements you wish to order : 4

Enter the names :
Lokesh Singh
Rahul Sinha
Rahul Gupta
Ajay Singh

Sorted strings are :
Ajay Singh
Lokesh Singh
Rahul Gupta
Rahul Sinha

We hope you all have enjoyed the of Printing Strings into Lexicographical order or Alphabetical order. If you have any doubts or issues ask us in form of comments.

 

 

6 COMMENTS

  1. I am so glade that you help understand and so solve coding problem, and I hope you keep on delivering such a nice service whenever asked.-Emmanuel ( Kampala International University, IT student)

LEAVE A REPLY