C program to sort names in alphabetical order


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 :
");    scanf("%d",&n);    printf("Enter names in any order:
");    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("
The sorted order of names are:
");    for(i=0;i<n;i++){       printf("%s
",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

Updated on: 26-Mar-2021

51K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements