Write a C program which will prompt the user to enter some words and then sort the words in alphabetical order and display them.
#include <stdio.h>
#include <string.h>
void accept(char str[][80], int s);
void display(char str[][80], int s);
void bsort(char str[][80], int s);
int main()
{
char text[10][80], n;
printf("Number of strings you want to enter : ");
scanf("%d", &n);
accept(text, n);
printf("\nBefore sorting");
display(text, n);
bsort(text, n);
printf("\nAfter sorting");
display(text, n);
return 0;
}
void accept(char str[][80], int s)
{
int i;
for (i = 0; i < s; i++)
{
printf("Enter string %d : ", i + 1);
gets(str[i]);
}
}
void display(char str[][80], int s)
{
int i;
printf("\n");
for (i = 0; i < s; i++)
{
puts(str[i]);
}
}
void bsort(char str[][80], int s)
{
int i, j;
char temp[80];
for (i = 0; i < s - 1; i++)
{
for (j = 0; j < (s - 1-i); j++)
{
if (strcmp(str[j], str[j + 1]) > 0)
{
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
}
Number of strings you want to enter : 4
Enter string 1 : Indonesia
Enter string 2 : Pakistan
Enter string 3 : India
Enter string 4 : Bangladesh
Before sorting
Indonesia
Pakistan
India
Bangladesh
After sorting
Bangladesh
India
Indonesia
Pakistan