C Program to sort a set of strings alphabetically
Program
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char str[10][20], temp[20];
int i, j, n;
printf("Enter the number of strings you would like to enter\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter %d string: ", i + 1);
scanf("%s", str[i]);
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (strcmp(str[j], str[j + 1]) > 0)
{
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
printf("Sorted List :\n");
for (i = 0; i < n; i++)
printf("%s\n", str[i]);
}
Output
Enter the number of strings you would like to enter
4
Enter 1 string: zing
Enter 2 string: aardvark
Enter 3 string: karma
Enter 4 string: opus
Sorted List :
aardvark
karma
opus
zing