C program to sort names or strings in alphabetical order

C program to sort names:

In this post, we will learn how to sort names or strings in alphabetical order in C. The program will take the names as user input, sort them and print them out.

We will use the below algorithm for this program:

  • Take the names from the user one by one
  • Sort the names alphabetically
  • Print the sorted names

C program :

#include<stdio.h>
#include<string.h>

int main(){
	int i, j, count;

	printf("Enter total number of names : ");
	scanf("%d", &count);

	char originalNames[count][20], sortedNames[count][20], tempVar[20];

	for(i = 0; i < count; i++){
		printf("Enter name %d : ",i+1);
		scanf("%s", originalNames[i]);
		strcpy(sortedNames[i], originalNames[i]);
	}

	for(i = 0; i < count - 1; i++){
		for(j = i+1; j < count; j++){
			if(strcmp(sortedNames[i], sortedNames[j]) > 0){
				strcpy(tempVar, sortedNames[i]);
				strcpy(sortedNames[i], sortedNames[j]);
				strcpy(sortedNames[j], tempVar);
			}
		}
	}

	printf("Sorted names :\n");

	for(i = 0; i< count; i++){
		printf("%s\n", sortedNames[i]);
	}
}

Explanation of this program:

String comparison is difficult in C programming. But we can use the header file string.h that provides different methods to work with strings. We will use strcmp and strcpy in this example. strcmp is used to compare two strings and strcpy is used to copy one string to a different variable.

  • originalNames array is used to store the original names entered by the user. sortedNames array stores the sorted names. Note that these are two dimensional arrays and we are assigning the size after reading the total number of names i.e. count from the user. It can hold maximum of 20 characters for each word.
  • The first for loop is used to read the names one by one. We are reading the names and storing them in both originalNames and sortedNames arrays.
  • The second for loop is used to do the sorting. Here, we are using two loops. The outer loop iterate through the names one by one and the inner loop compares each one with the others i.e. all names to the right of it.
  • strcmp is used to compare the name at position i with the word at position j. If they are not sorted, we are using one temporary variable to sort them. Note that we are working on the sortedNames array. The originalNames remains same.
  • Finally, we are printing out the sorted names or the values of sortedNames.

Sample output:

Enter total number of names : 5
Enter name 1 : Alex
Enter name 2 : Bob
Enter name 3 : Albert
Enter name 4 : Chandler
Enter name 5 : Daisy
Sorted names :
Albert
Alex
Bob
Chandler
Daisy

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊