Unit 8
Character Arrays and Strings
Character array
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
Char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
Char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string −
#include <stdio.h>
Int main () {
Char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Printf("Greeting message: %s\n", greeting );
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. | Function & Purpose |
1 | Strcpy(s1, s2); Copies string s2 into string s1. |
2 | Strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3 | Strlen(s1); Returns the length of string s1. |
4 | Strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | Strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. |
6 | Strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. |
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>
Int main () {
Char str1[12] = "Hello";
Char str2[12] = "World";
Char str3[12];
Int len ;
/* copy str1 into str3 */
Strcpy(str3, str1);
Printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
Strcat( str1, str2);
Printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
Len = strlen(str1);
Printf("strlen(str1) : %d\n", len );
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Strcpy( str3, str1) : Hello
Strcat( str1, str2): HelloWorld
Strlen(str1) : 10
Numeric Array
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −
Type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −
Double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
Double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
Double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
Balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
Double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. Declaration, assignment, and accessing arrays −
#include <stdio.h>
Int main () {
Int n[ 10 ]; /* n is an array of 10 integers */
Int i,j;
/* initialize elements of array n to 0 */
For ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
For (j = 0; j < 10; j++ ) {
Printf("Element[%d] = %d\n", j, n[j] );
}
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −
Sr.No. | Concept & Description |
1 | Multi-dimensional arrays C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. |
2 | Passing arrays to functions You can pass to the function a pointer to an array by specifying the array's name without an index. |
3 | Return array from a function C allows a function to return an array. |
4 | Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index. |
Null Character
A null character is a character with all its bits set to zero. Therefore, it has a numeric value of zero and can be used to represent the end of a string of characters, such as a word or phrase. This helps programmers determine the length of strings. In practical applications, such as database and spreadsheet programs, null characters are used as fillers for spaces.
String is nothing but a collection of characters in a linear sequence. 'C' always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks.
Example, "Welcome to the world of programming!"
'C' provides standard library <string.h> that contains many functions which can be used to perform complicated string operations easily.
Declare and initialize a String
A string is a simple array with char as a data type. 'C' language does not directly support string as a data type. Hence, to display a string in 'C', you need to make use of a character array.
The general syntax for declaring a variable as a string is as follows,
Char string_variable_name [array_size];
The classic string declaration can be done as follow:
Char string_name[string_length] = "string";
The size of an array must be defined while declaring a string variable because it used to calculate how many characters are going to be stored inside the string variable. Some valid examples of string declaration are as follows,
Char first_name[15]; //declaration of a string variable
Char last_name[15];
The above example represents string variables with an array size of 15. This means that the given character array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL character '\0' to the character array created.
Let's study the initialization of a string variable. Following example demonstrates the initialization of a string variable,
Char first_name[15] = "ANTHONY";
Char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is required at end in this declaration
Char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
Char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */
Char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/
In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks.
'C' also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way,
Char first_name[ ] = "NATHAN";
The name of a string acts as a pointer because it is basically an array.
String Input: Read a String
When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the variable address because an array name acts as a pointer. For example:
#include <stdio.h>
Int main() {
Char name[10];
Int age;
Printf("Enter your first name and age: \n");
Scanf("%s %d", name, &age);
Printf("You entered: %s %d",name,age);
}
Output:
Enter your first name and age:
John_Smith 48
The problem with the scanf function is that it never reads an entire string. It will halt the reading process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a whitespace character occurs between the two names. The scanf function will only read Guru99.
In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops reading when a newline is reached (the Enter key is pressed).For example:
#include <stdio.h>
Int main() {
Char full_name[25];
Printf("Enter your full name: ");
Gets(full_name);
Printf("My full name is %s ",full_name);
Return 0;
}
Output:
Enter your full name: Dennis Ritchie
My full name is Dennis Ritchie
Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example:
#include <stdio.h>
Int main() {
Char name[10];
Printf("Enter your name plz: ");
Fgets(name, 10, stdin);
Printf("My name is %s ",name);
Return 0;}
Output:
Enter your name plz: Carlos
My name is Carlos
The fgets() arguments are :
- The string name,
- The number of characters to read,
- Stdin means to read from the standard input which is the keyboard.
String Output: Print/Display a String
The standard printf function is used for printing or displaying a string on an output device. The format specifier used is %s
Example,
Printf("%s", name);
String output is done with the fputs() and printf() functions.
Fputs() function
The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen.For example:
#include <stdio.h>
Int main()
{char town[40];
Printf("Enter your town: ");
Gets(town);
Fputs(town, stdout);
Return 0;}
Output:
Enter your town: New York
New York
Puts function
The puts function prints the string on an output device and moves the cursor back to the first position. A puts function can be used in the following way,
#include <stdio.h>
Int main() {
Char name[15];
Gets(name); //reads a string
Puts(name); //displays a string
Return 0;}
The syntax of this function is comparatively simple than other functions.
The string library
The standard 'C' library provides various functions to manipulate the strings within a program. These functions are also called as string handlers. All these handlers are present inside <string.h> header file.
Function | Purpose |
Strlen() | This function is used for finding a length of a string. It returns how many characters are present in a string excluding the NULL character. |
Strcat(str1, str2) | This function is used for combining two strings together to form a single string. It Appends or concatenates str2 to the end of str1 and returns a pointer to str1. |
Strcmp(str1, str2) | This function is used to compare two strings with each other. It returns 0 if str1 is equal to str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2. |
Lets consider the program below which demonstrates string library functions:
#include <stdio.h>
#include <string.h>
Int main () {
//string initialization
Char string1[15]="Hello";
Char string2[15]=" World!";
Char string3[15];
Int val;
//string comparison
Val= strcmp(string1,string2);
If(val==0){
Printf("Strings are equal\n");
}
Else{
Printf("Strings are not equal\n");
}
//string concatenation
Printf("Concatenated string:%s",strcat(string1,string2)); //string1 contains hello world!
//string length
Printf("\nLength of first string:%d",strlen(string1));
Printf("\nLength of second string:%d",strlen(string2));
//string copy
Printf("\nCopied string is:%s\n",strcpy(string3,string1)); //string1 is copied into string3
Return 0;
}
Output:
Strings are not equal
Concatenated string:Hello World!
Length of first string:12
Length of second string:7
Copied string is:Hello World!
Other important library functions are:
- Strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
- Strncpy(str1, str2, n) This function is used to copy a string from another string. Copies the first n characters of str2 to str1
- Strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if character not found.
- Strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c in str1, or NULL if character not found.
- Strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found.
- Strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1 and returns a pointer to str1.
- Strlwr() :to convert string to lower case
- Strupr() :to convert string to upper case
- Strrev() : to reverse string
Converting a String to a Number
In C programming, we can convert a string of numeric characters to a numeric value to prevent a run-time error. The stdio.h library contains the following functions for converting a string to a number:
- Int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first character is not a number or no numbers are encountered.
- Double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is returned if the first character is not a number or no numbers are encountered.
- Long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer value. 0 is returned if the first character is not a number or no numbers are encountered.
The following program demonstrates atoi() function:
#include <stdio.h>
Int main()
{char *string_id[10];
Int ID;
Printf("Enter a number: ");
Gets(string_id);
ID = atoi(string_id);
Printf("you enter %d ",ID);
Return 0;}
Output:
Enter a number: 221348
You enter 221348
- A string pointer declaration such as char *string = "language" is a constant and cannot be modified.
Summary
- A string is a sequence of characters stored in a character array.
- A string is a text enclosed in double quotation marks.
- A character such as 'd' is not a string and it is indicated by single quotation marks.
- 'C' provides standard library functions to manipulate strings in a program. String manipulators are stored in <string.h> header file.
- A string must be declared or initialized before using into a program.
- There are different input and output string functions, each one among them has its features.
- Don't forget to include the string library to work with its functions
- We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes.
- We can manipulate different strings by defining a string array.
Formatted output of string
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.
The format specifier in printf() and scanf() are mostly the same but there is some difference which we will see.
Printf(char *format, arg1, arg2, …)
This function prints the character on standard output and returns the number of character printed the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.).
Between both, there can be elements governing the printing format. Below is its description
- A minus(-) sign tells left alignment.
- A number after % specifies the minimum field width to be printed if the characters are less than the size of width the remaining space is filled with space and if it is greater than it printed as it is without truncation.
- A period( . ) symbol separate field width with the precision.
Precision tells the maximum number of digits in integer, characters in string and number of digits after decimal part in floating value.
Lets see these..
Character format specifier : %c
#include <stdio.h> Int main() { Char ch = 'A'; Printf("%c\n", ch); Return 0; } |
Output:
A
Integer format specifier : %d, %i
#include <stdio.h> Int main() { Int x = 45, y = 90; Printf("%d\n", x); Printf("%i\n", x); Return 0; } |
Output:
45
45
Floating-point format specifier : %f, %e or %E
#include <stdio.h> Int main() { Float a = 12.67; Printf("%f\n", a); Printf("%e\n", a); Return 0; } |
Output:
12.670000
1.267000e+01
Unsigned Octal number for integer : %o
#include <stdio.h> Int main() { Int a = 67; Printf("%o\n", a); Return 0; } |
Output:
103
Unsigned Hexadecimal for integer : %x, %X
#include <stdio.h> Int main() { Int a = 15; Printf("%x\n", a); Return 0; } |
Output:
f
String printing : %s
#include <stdio.h> Int main() { Char a[] = "geeksforgeeks"; Printf("%s\n", a); Return 0; } |
Output:
Geeksforgeeks
More formatting
#include <stdio.h> Int main() { Char str[] = "geeksforgeeks"; Printf("%20s\n", str); Printf("%-20s\n", str); Printf("%20.5s\n", str); Printf("%-20.5s\n", str); Return 0; } |
Output:
Geeksforgeeks
Geeksforgeeks
Geeks
Geeks
Scanf(char *format, arg1, arg2, …)
This function take input using standard input (keyboard) and store it in variable accordingly. It returns the number of items successfully read. Formal parameter arg1, agr2, .. Must be a pointer
Decimal integer : %d
#include <stdio.h> Int main() { Int a = 0; Scanf("%d", &a); // input is 45 Printf("%d\n", a); Return 0; } |
Integer may be octal or in hexadecimal : %i
#include <stdio.h> Int main() { Int a = 0; Scanf("%i", &a); // input is 017 (octal of 15 ) Printf("%d\n", a); Scanf("%i", &a); // input is 0xf (hexadecimal of 15 ) Printf("%d\n", a); Return 0; } |
Double floating-point number : %lf
#include <stdio.h> Int main() { Double a = 0.0; Scanf("%lf", &a); // input is 45.65 Printf("%lf\n", a); Return 0; } |
Output:
45.650000
String input : %s
#include <stdio.h> Int main() { Char str[20]; Scanf("%s", str); // input is geeksforgeeks Printf("%s\n", str); Return 0; } |
Output:
P@
Character input : %c
#include <stdio.h> Int main() { Char ch; Scanf("%c", &ch); // input is A Printf("%c\n", ch); Return 0; } |
Many other format specifiers are also there
1.%u for an unsigned integer.
2.%lld for long long int.
3.%o octal integer without leading zero
4.%x hexadecimal integer without 0x before the number.
Arithmetic operations on characters
Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings. When the characters are used with the arithmetic operations, it converts them into integer value automatically i.e. ASCII value of characters.
Here is an example of character arithmetic in C language,
Example
#include <stdio.h>
Int main(){
Char s = 'm';
Char t = 'z' - 'y';
Printf("%d\n", s);
Printf("%c\n", s);
Printf("%d\n", (s+1));
Printf("%c\n", (s+1));
Printf("%d\n", (s-1));
Printf("%c\n", (s-1));
Printf("%d\n", t);
// printf("%c", t);
Return 0;
}
Output
Here is the output −
109
m
110
n
108
l
1
The string.h header defines one variable type, one macro, and various functions for manipulating arrays of characters.
Library Variables
Following is the variable type defined in the header string.h −
Sr.No. | Variable & Description |
1 | Size_t This is the unsigned integral type and is the result of the sizeof keyword. |
Library Macros
Following is the macro defined in the header string.h −
Sr.No. | Macro & Description |
1 | NULL This macro is the value of a null pointer constant. |
Library Functions
Following are the functions defined in the header string.h −
Sr.No. | Function & Description |
1 | Void *memchr(const void *str, int c, size_t n) Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str. |
2 | Int memcmp(const void *str1, const void *str2, size_t n) Compares the first n bytes of str1 and str2. |
3 | Void *memcpy(void *dest, const void *src, size_t n) Copies n characters from src to dest. |
4 | Void *memmove(void *dest, const void *src, size_t n) Another function to copy n characters from str2 to str1. |
5 | Void *memset(void *str, int c, size_t n) Copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str. |
6 | Char *strcat(char *dest, const char *src) Appends the string pointed to, by src to the end of the string pointed to by dest. |
7 | Char *strncat(char *dest, const char *src, size_t n) Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long. |
8 | Char *strchr(const char *str, int c) Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the argument str. |
9 | Int strcmp(const char *str1, const char *str2) Compares the string pointed to, by str1 to the string pointed to by str2. |
10 | Int strncmp(const char *str1, const char *str2, size_t n) Compares at most the first n bytes of str1 and str2. |
11 | Int strcoll(const char *str1, const char *str2) Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location. |
12 | Char *strcpy(char *dest, const char *src) Copies the string pointed to, by src to dest. |
13 | Char *strncpy(char *dest, const char *src, size_t n) Copies up to n characters from the string pointed to, by src to dest. |
14 | Size_t strcspn(const char *str1, const char *str2) Calculates the length of the initial segment of str1 which consists entirely of characters not in str2. |
15 | Char *strerror(int errnum) Searches an internal array for the error number errnum and returns a pointer to an error message string. |
16 | Size_t strlen(const char *str) Computes the length of the string str up to but not including the terminating null character. |
17 | Char *strpbrk(const char *str1, const char *str2) Finds the first character in the string str1 that matches any character specified in str2. |
18 | Char *strrchr(const char *str, int c) Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str. |
19 | Size_t strspn(const char *str1, const char *str2) Calculates the length of the initial segment of str1 which consists entirely of characters in str2. |
20 | Char *strstr(const char *haystack, const char *needle) Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack. |
21 | Char *strtok(char *str, const char *delim) Breaks string str into a series of tokens separated by delim. |
22 | Size_t strxfrm(char *dest, const char *src, size_t n) Transforms the first n characters of the string src into current locale and places them in the string dest. |
Sometimes we often use lists of character strings, such as the list of names of students in a class, a list of names of employees in an organization, a list of places, etc. A list of names can be treated as a table of string. To store the entire list we use a 2d array of strings in C language.
The array of characters is called a string. “Hi”, “Hello”, and e.t.c are the examples of String. Similarly, the array of Strings is nothing but a two-dimensional (2D) array of characters. To declare an array of Strings in C, we must use the char data type.
Example of two dimensional characters or the array of Strings is,
Char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};
Declaration of the array of strings
Syntax:-
Char string-array-name[row-size][column-size];
Here the first index (row-size) specifies the maximum number of strings in the array, and the second index (column-size) specifies the maximum length of every individual string.
For example, char language[5][10]; In the “language” array we can store a maximum of 5 Strings and each String can have a maximum of 10 characters.
In C language, each character take 1 byte of memory. For the “language” array it will allocate 50 bytes (1*5*10) of memory. Where each String will have 10 bytes (1*10) of memory space.
Initialization of array of strings
Two dimensional (2D) strings in C language can be directly initialized as shown below,
Char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};
Char largestcity[6][15] =
{"Tokyo", "Delhi", "Shanghai", "Mumbai", "Beijing", "Dhaka"};
The two dimensional (2D) array of Strings in C also can be initialized as,
Char language[5][10] ={
{'J','a','v','a','\0'},
{'P','y','t','h','o','n','\0'},
{'C','+','+','\0'},
{'H','T','M','L','\0'},
{'S','Q','L','\0'}
};
Since it is a two-dimension of characters, so each String (1-D array of characters) must end with null character i.e. ‘\0’
The second way of declaring the array of strings is a lengthy process, and other programmers can’t read them easily compared to the previous declaration, that why most of the time we prefer the first declaration.
The each String in this array can be accessed by using its index number. The index of array always starts with 0.
Language[0] => "Java";
Language[1] => "Python";
Language[2] => "C++";
Language[3] => "HTML";
Language[4] => "SQL";
Note1:- the number of characters (column-size) must be declared at the time of the initialization of the two-dimensional array of strings.
// it is valid
Char language[ ][10] = {"Java", "Python", "C++", "HTML", "SQL"};
But that the following declarations are invalid.
// invalid
Char language[ ][ ] = {"Java", "Python", "C++", "HTML", "SQL"};
// invalid
Char language[5][ ] = {"Java", "Python", "C++", "HTML", "SQL"};
Note2:- Once we initialize the array of String then we can’t directly assign a new String.
Char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};
// now, we can't directly assign a new String
Language[0] = "Kotlin"; // invalid
// we must copy the String
Strcpy(language[0], "Kotlin"); // valid
// Or,
Scanf(language[0], "Kotlin"); // valid
Reading and displaying 2d array of strings in C
The two-dimensional array of strings can be read by using loops. To read we can use scanf(), gets(), fgets() or any other methods to read the string.
// reading strings using for loop
For(i=0;i<n;i++)
{
Scanf("%s[^\n]",name[i]);
}
Or,
// reading strings using while loop
Int i=0;
While(i<n)
{
Scanf("%s[^\n]",name[i]);
i++;
}
The two-dimensional array of strings can be displayed by using loops. To display we can use printf(), puts(), fputs() or any other methods to display the string.
// displaying strings using for loop
For(i=0;i<n;i++)
{
Puts(name[i]);
}
Or,
// displaying strings using while loop
Int i=0;
While (i<n)
{
Puts(name[i]);
i++;
}
Sample program to read the 2D array of characters or array of String in C
#include<stdio.h>
Int main()
{
// declaring and initializing 2D String
Char language[5][10] =
{"Java", "Python", "C++", "HTML", "SQL"};
// Dispaying strings
Printf("Languages are:\n");
For(int i=0;i<5;i++)
Puts(language[i]);
Return 0;
}
Output:-
Languages are:
Java
Python
C++
HTML
SQL
Program:- Write a program to read and display a 2D array of strings in C language.
#include<stdio.h>
Int main()
{
Char name[10][20];
Int i,n;
Printf("Enter the number of names (<10): ");
Scanf("%d",&n);
// reading string from user
Printf("Enter %d names:\n",n);
For(i=0; i<n; i++)
Scanf("%s[^\n]",name[i]);
// Dispaying strings
Printf("\nEntered names are:\n");
For(i=0;i<n;i++)
Puts(name[i]);
Return 0;
}
Output:-
Enter the number of names (<10): 5
Enter 5 names:
Emma
Olivia
Ava
Isabella
Sophia
Entered names are:
Emma
Olivia
Ava
Isabella
Sophia