C program to Sort Names in Alphabetical Order

Write a C program to sort names in alphabetical order. This C example allows entering multiple strings or names and sorting them in alphabetical order using for loop. The if statement (if (strcmp(str[i], str[j]) > 0) ) compares each string with the other. The strcpy function will copy that string to temp and then alter their positions based on the result.

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

int main()
{
	char str[50][50], temp[50];
	int i, j, number;

	printf("How many Strings you want to enter = ");
	scanf("%d", &number);

	printf("Please Enter String one by one\n");
	for (i = 0; i <= number; i++)
	{
		fgets(str[i], sizeof str[i], stdin);
	}
	for (i = 0; i <= number; i++)
	{
		for (j = i + 1; j <= number; j++)
		{
			if (strcmp(str[i], str[j]) > 0)
			{
				strcpy(temp, str[i]);
				strcpy(str[i], str[j]);
				strcpy(str[j], temp);
			}
		}
	}

	printf("\n***** The Order of the  Sorted Strings *****");
	for (i = 0; i <= number; i++)
	{
		puts(str[i]);
	}
	return 0;
}
C program to Sort Names in Alphabetical Order

In this C program, the sortNamesAlphabetically function will sort the set of strings or string names in alphabetical order.

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

char str[50][50], temp[50];
int i, j, number;

void sortNamesAlphabetically()
{
	for (i = 0; i <= number; i++)
	{
		for (j = i + 1; j <= number; j++)
		{
			if (strcmp(str[i], str[j]) > 0)
			{
				strcpy(temp, str[i]);
				strcpy(str[i], str[j]);
				strcpy(str[j], temp);
			}
		}
	}
}
int main()
{
	printf("How many Strings you want to enter = ");
	scanf("%d", &number);

	printf("Please Enter String one by one\n");
	for (i = 0; i <= number; i++)
	{
		fgets(str[i], sizeof str[i], stdin);
	}

	sortNamesAlphabetically();

	printf("\n***** The Order of the  Sorted Strings *****");
	for (i = 0; i <= number; i++)
	{
		puts(str[i]);
	}
	return 0;
}
How many Strings you want to enter = 6
Please Enter String one by one
usa
india
uk
japan 
china
australia

***** The Order of the  Sorted Strings *****

australia

china

india

japan

uk

usa