C program to sort the string using 2D array

Programming Example

Write a program to initialize a array with 5 String maximum length of 10 char and arrange the string in alphabetical order.

Solution

#include<stdio.h>
int main()
{
char arr[5][10]={"white","red","green","yellow","blue"};
char temp[10];
int i,j;
printf("before sorting:\n");
for(i=0;i<5;i++)
	printf("%s\n",arr[i]);

for(i=0;i<5;i++)
	for(j=i+1;j<5;j++)
		if(strcmp(arr[i],arr[j])>0)
		{
			strcpy(temp,arr[i]);
			strcpy(arr[i],arr[j]);
			strcpy(arr[j],temp);
		}
		printf("\nafter sorting:\n");
		for(i=0;i<5;i++)
		printf("%s\n",arr[i]);
}
Output

before sorting:

white

red

green

yellow

blue


after sorting:

blue

green

red

white

yellow

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad