# C Program to Sort N Names in Alphabetical Order

## Problem:

Write a C program to sort n names/strings in alphabetical order. Write a program that accepts n names/words and displays them in alphabetical or ascending order.

## Solution:

In this program we are going to use standard library function strcmp() to compare strings and to sort them in alphabetical order.

## Sort n names alphabetically in C:

C program to sort names in alphabetical order
``````/* Aim: Write a C program to sort names in alphabetical order.*/

#include<stdio.h>
#include<string.h>
#define size 100

void alphabetical_order(int n); // alphabetical_order() Function Prototype

int main()
{
int n;

printf("\n How many names/strings do you want to sort:- ");
scanf("%d",&n);

printf("\n");

alphabetical_order(n);
printf("\n");

} // End of main

// alphabetical_order() function

void alphabetical_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 Names in sorted alphabetical order:- ");

for(i=0;i<n;++i)
printf("\n %s",list[i]);

} // End of alphabetical_order() Function

/* Output of above code:-

How names/strings do you want to sort:- 5

Computer
Science
CPrograms
Lists

Names in sorted alphabetical order:-
CPrograms
Computer
Lists
Science

*/``````