C program to sort names in alphabetical order

CServer Side ProgrammingProgramming

User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function.

An array of characters (or) collection of characters is called a string.

Declaration

Following is the declaration for an array −

char stringname [size];

For example, char string[50]; string of length 50 characters.

Initialization

  • Using single character constant
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants
char string[10] = "Hello":;

Accessing

There is a control string "%s" used for accessing the string till it encounters ‘\0’

strcpy ( )

This function is used for copying source string into destination string.

The length of the destination string is greater than or equal to the source string.

The syntax for strcpy() function is as follows −

strcpy (Destination string, Source String);

For example,

char a[50];             char a[50];
strcpy ("Hello",a);      strcpy ( a,"hello");
output: error           output: a= "Hello"

The logic used to sort the names in alphabetical order is as follows −

for(i=0;i<n;i++){
   for(j=i+1;j<n;j++){
      if(strcmp(str[i],str[j])>0){
         strcpy(s,str[i]);
         strcpy(str[i],str[j]);
         strcpy(str[j],s);
      }
   }
}

Program

Following is the C program to sort names in alphabetical order −

#include<stdio.h>
#include<string.h>
main(){
   int i,j,n;
   char str[100][100],s[100];
   printf("Enter number of names :\n");
   scanf("%d",&n);
   printf("Enter names in any order:\n");
   for(i=0;i<n;i++){
      scanf("%s",str[i]);
   }
   for(i=0;i<n;i++){
      for(j=i+1;j<n;j++){
         if(strcmp(str[i],str[j])>0){
            strcpy(s,str[i]);
            strcpy(str[i],str[j]);
            strcpy(str[j],s);
         }
      }
   }
   printf("\nThe sorted order of names are:\n");
   for(i=0;i<n;i++){
      printf("%s\n",str[i]);
   }
}

Output

When the above program is executed, it produces the following result −

Enter number of names:
5
Enter names in any order:
Pinky
Lucky
Ram
Appu
Bob
The sorted order of names is:
Appu
Bob
Lucky
Pinky
Ram
raja
Published on 26-Mar-2021 07:47:46
Advertisements