C Program to Sort Names in Alphabetical Order

In this tutorial, you will learn and get code about sorting of given names by user (at run-time) in alphabetical order. For example, if user provides following 5 names as input:

  • Emma
  • William
  • Alexander
  • Sophia
  • Benjamin

Then the output will be

  • Alexander
  • Benjamin
  • Emma
  • Sophia
  • William

As you can see, all the 5 names gets arranged in alphabetical order (ascending). Let's move on and implement it in a C program.

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
   char str[5][20], t[20];
   int i, j;
   printf("Enter any string (5 names):\n");
   for(i=0; i<5; i++)
      scanf("%s", str[i]);
   for(i=1; i<5; i++)
   {
      for(j=1; j<5; j++)
      {
         if(strcmp(str[j-1], str[j])>0)
         {
            strcpy(t, str[j-1]);
            strcpy(str[j-1], str[j]);
            strcpy(str[j], t);
         }
      }
   }
   printf("\nStrings (Names) in alphabetical order:\n");
   for(i=0; i<5; i++)
      printf("%s\n", str[i]);
   getch();
   return 0;
}

The program was written under Code::Blocks IDE, therefore after successful build and run, here is the sample run:

c program sort string

Now supply any five names as string and press ENTER key to see the string with its each word sorted in alphabetical order as shown here in the second snapshot.

You have to provide all the 5 names as string one by one. That is, supply first name say Emma and press ENTER key, then supply second name say William and press ENTER key and so on.

c sort words in alphabetical order

As the function used here to get the string input from user is scanf(), therefore you can also provide all the 5 names as string in one line say Emma William Alexander Sophia Benjamin. Here is the final snapshot of the sample run in this case:

sort each word in string alphabetical order

Here are some of the main steps used in above program:

  • Receive the list of 5 words as string using string array
  • Using for loop, check first character of all the words to compare and arrange in alphabetical order
  • That is, use the function strcmp() to compare the string. That is to check whether the first character of the first word is less than the first character of the second word or not
  • If it is, then using the strcpy() function, reverse the word with each and other and continue to check for the next word inside the same string
  • That is, again check whether the second word's first character is less than the third word's first character or not
  • If it is, then again using the strcpy() function, reverse the word with each other and so on.
  • Now print the value of all the five words as string on output
  • You will see that all the five words are sorted or arranged in alphabetical order according to its first character of the word

C Online Test


« Previous Program Next Program »



Like/Share Us on Facebook 😋