A two-dimensional array is used to create an array of strings consider the statement
char name [30] [10];
Here 30 indicates the number of strings and 10 indicates the maximum length of each string. This is also used to create a table ‘Table of strings. The two dimensional character array shown below can store a table. For example:
char city [5] [20] ={“Cuttack”, “Berhampur”, “Sambalpur”, “Puri”, “Bhubaneswar”};
To access the name of the list, we must write,
city [i] where i = 0 to 4. Thus
city [0] indicates Cuttack,
city [1] to Berhampur,
city [2] to Sambalpur,
city [3] to puri and
city [4] to Bhubaneswar.
It may be observed that the table thus created using a two dimensional character is nothing but a column of strings. One fine example to illustrate the use of two dimensional array of strings is name sorting. Here is a program to perform this task.
Program – program to sort strings of names
#include <stdio.h>
void main ()
{
char names [20] [10], temp [10], c;
int i, j, k, n;
clrscr ();
n = 0;
printf (“Enter names one per line\n”);
printf (“Terminate with string END\n”);
scanf (“%s”, names [n]);
while (strcmp (names[n], “END”)>0)
{
n++;
scanf (“%s”, names[n]);
}
printf(“\n”);
for (i=0; i <n; i ++)
printf (“%10s”, names[i]);
printf (“\n”);
printf (“\n”);
printf (“Total names = %d\n”, n);
/*selection sorting*/
for (i=0; i<n-1; i ++)
for (j=i+1; j<n; j++)
{
if (strcmp (names [1], names [j])>0)
{
Strcpy (temp, names [i]);
Strcpy (names [i], names [j]);
Strcpy (names[j], temp);
}
}
printf (“\nSorted Names:\n”);
for (i = 0; i <n; i++)
printf (“%10s”, names [i]);
printf(“\n”);
getch ();
}
Output
Enter names one per line
Terminate with string END
santosh
alok
amiya
bikram
prafulla
santosh alok amiya bikram Prafulla
Total names = 5
Sorted names:
alok amiya bikram prafulla santosh
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc