Table of Contents
show
A string is an array of characters; so, an array of strings is an array of arrays of characters. Of course, the maximum size is the same for all the strings stored in a two dimensional array. We can declare a two dimensional character array of MAX strings of size SIZE as follows:
char names[MAX][SIZE];
Example
char name[2][6];
name[0] | J | 0 | h | n | \0 | |
name[1] | S | u | e | \0 |
Program: To sort names in Alphabetical order
#include<stdio.h>
#include<string.h>
int main()
{
char name[10][8],tname[10][8],temp[8];
int i,j,n;
printf("Enter number of names");
scanf("%d",&n);
printf("\n Enter names\n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
strcpy(tname[i],name[i]);
}
printf("\nBefore sorting\n");
for(i=0;i<n;i++)
{
printf("%s\n",tname[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j]) >0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("\nAfter sorting\n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
return 0;
}
Output
Enter number of names5
Enter names
sue
john
lilly
abu
denie
Before sorting
sue
john
lilly
abu
denie
After sorting
abu
denie
john
lilly
sue
Views: 0