Preview
Array of strings in c language with examples
It is actually a two dimensional array of char type.
Example: char n[6][10];
In above example, n is an array of strings which can contain 6 string values. Each of the string value can contain maximum 10 characters.
1. Initialization of array of strings
We can initialize an array of strings just as we initialize a normal array The way to initialize an array of strings is
char var_name[R][C]={List of String values};
char specifies that we are declaring an array of strings.
Var_name refers to the array of strings defined by the programmer. The string array name should follow all the rules of a valid identifier of C Language.
[ ] [ ] Pair of square brackets specifies that it is an array of strings.
R specifies the maximum number of string values which can be stored in string array.
C specifies the maximum number of characters which can be stored in each string value stored in string array.
List of String values specifies various string values which are to be stored into string array. The list of string values must be enclosed between braces.
Example:char names[3][20]={“Lovejot”,”Ajay”,”Amit”};
Program |
#include<stdio.h> int main() { char names[3][20]={“Lovejot”,”Ajay”,”Amit”}; int i; printf(”\nElements of string array are”); for(i=0;i<3;i++) printf(“\n%s”,names[i]); return(0); } |
Output |
Elements of string array are Lovejot Ajay Amit |
2. Reading and displaying array of strings
We can read and display an array of strings just as we read and display an array of other data types.
Program |
#include<stdio.h> int main() { char n[3][20]; int i; printf(”\nEnter three strings\n”); for(i=0;i<3;i++) gets(n[i]);printf(”\nElements of array are”); for(i=0;i<3;i++) printf(“\n%s”,n[i]); return (0); } |
Output |
Enter three string Lovejot Ajay AmitElements of array are Lovejot Ajay Amit |
Best Books of Computer Science