This is a C Program to sort the names in an alphabetical order.
Problem Description
The program will accept some names from the user as input & then sorts them in an alphabetical order using string operation.
Problem Solution
1. Create a 2D character array to store names of some fixed size.
2. Take names as input from users using for loop.
3. Now, sort this array of names using Selection sort.
4. Make a nested for loop, where the upper loop extracts each name and inner loop compares this name by the rest of the names below it.
5. After executing both the loops, rearranging all the names, finally an array of alphabetically sorted array will be obtained.
Program/Source Code
Here is source code of the C program to sort the names in an alphabetical order. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program to read N names, store them in the form of an array
* and sort them in alphabetical order. Output the given names and
* the sorted names in two columns side by side.
*/
#include
#include
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
printf(“Enter %d names n \n”, n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf(“\n—————————————-\n”);
printf(“Input NamestSorted names\n”);
printf(“——————————————\n”);
for (i = 0; i < n; i++) { printf("%s\t\t%s\n", tname[i], name[i]); } printf("------------------------------------------\n"); }