Programming Examples
C program to sort the string using 2D array
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