www.computerscienceai.com provides resources like python programs, c programs, java programs, c++ programs, php programs, html and css free resources, articles and "how to" tutorials on computer, science, artificial intelligence and tech world.
C Program to Sort Words/Names in Alphabetical Order
Problem:
Write a C program to sort words in alphabetical order. Write a program that accepts n names/words and displays them in dictionary/alphabetical/ascending order (Lexicographical Order).
C Program / Source Code:
Here is the source code of C program to sort words in alphabetical order
/* Aim: Write a C program to sort words in alphabetical order.*/
#include<stdio.h>
#include<string.h>
#define size 100
void Dictionary_order(int n); // Dictionary_order() Function Prototype
void main()
{
int n;
printf("\n How many words/names do you want to sort:- ");
scanf("%d",&n);
printf("\n");
Dictionary_order(n);
printf("\n");
} // End of main
// Dictionary_order() function
void Dictionary_order(int n)
{
char list[n][20],temp[20];
int i,j;
for(i=0;i<n;i++)
scanf("%s",list[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(strcmp(list[i],list[j])>0)
{
strcpy(temp,list[i]);
strcpy(list[i],list[j]);
strcpy(list[j],temp);
}
}
printf("\n Words/Names in sorted alphabetical order:- ");
for(i=0;i<n;++i)
printf("\n %s",list[i]);
} // End of Dictionary_order() Function
/* Output of above code:-
How many/names words do you want to sort:- 5
Computer
Science
CPrograms
Lists
Linked
Words/Names in sorted alphabetical order:-
CPrograms
Computer
Linked
Lists
Science
*/