codescracker


c

C Program to Sort Strings in Alphabetical Order



« Previous Program Next Program »


Sort Strings in C

To sort strings in alphabetical order in C programming, you have to ask to the user to enter some set of strings (5 strings here). Now start comparing one strings with other and sort all the strings in alphabetical order then display all the strings in alphabetical order as shown here in the following program.

C Programming Code to Sort Strings in Alphabetical Order

Following C program ask to the user to enter five strings like names to sort them in alphabetical order then display the sorted strings in alphabetical order on the screen:

/* C Program - Sort Strings */
		
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
	clrscr();
	char str[5][20], t[20];
	int i, j;
	printf("Enter any five string (name) : ");
	for(i=0; i<5; i++)
	{
		scanf("%s",str[i]);
	}
	for(i=1; i<5; i++)
	{
		for(j=1; j<5; j++)
		{
			if(strcmp(str[j-1], str[j])>0)
			{
				strcpy(t, str[j-1]);
				strcpy(str[j-1], str[j]);
				strcpy(str[j], t);
			}
		}
	}
	printf("Strings (Names) in alphabetical order : \n");
	for(i=0; i<5; i++)
	{
		printf("%s\n",str[i]);
	}
	getch();
}

When the above c program is compile and executed, it will produce the following result:

c program sort string

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test