C Program to Find Total of Even Integers

C Program to Sort set of strings in Alphabetical Order

The following program key user to be ask to enter set of Strings and the program would sort and display them in ascending alphabetical order.

To Write a program that would sort list of names in alphabetical order. The C program to sort the strings in order is given in below simple example. It employs the method of bubble sorting described in Case Study 1 in the previous chapter.

C Program to Sort set of strings in Alphabetical Order

/* This program would sort the input strings in
 * an ascending order and would display the same
 */
#define ITEMS 5
#define MAXCHAR 20
main( )
{
   char string[ITEMS][MAXCHAR], dummy[MAXCHAR];
   int i = 0, j = 0;
/* Reading the list */
   printf ("Enter names of %d items \n ",ITEMS);
   while (i < ITEMS)
   scanf ("%s", string[i++]);
/* Sorting begins */
   for (i=1; i < ITEMS; i++) /* Outer loop begins */
   {
   for (j=1; j <= ITEMS-i ; j++) /*Inner loop begins*/
   {

   if (strcmp (string[j-1], string[j]) > 0)
   { /* Exchange of contents */
  strcpy (dummy, string[j-1]);
  strcpy (string[j-1], string[j]);
  strcpy (string[j], dummy );
 } } /* Inner loop ends */
} /* Outer loop ends */
 /* Sorting completed */
    printf ("\nAlphabetical list \n\n");
    for (i=0; i < ITEMS ; i++)
    printf ("%s", string[i]);
}

Output

Enter names of 5 items
London Manchester Delhi Paris Moscow
Alphabetical list
Delhi
London
Manchester
Moscow
Paris

Let me know if you find any difficulty in understanding this C Program with example and I would be glad to explain it further.

Also read : String Handling Function in C Programming

Online Training Tutorials