Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Arrays and Strings
  5. String Arrays

String Arrays

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]J0hn\0 
name[1]Sue\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

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments