DEV Community

venkatvarundaggupati
venkatvarundaggupati

Posted on

Character Arrays and Strings

Arrays:

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.

1-Dimensional array: It is a linear array that stores elements in a sequential order. Let us try to demonstrate this with an example: Let us say we have to store integers 2, 3, 5, 4, 6, 7. We can store it in an array of integer data type. The way to do it is:

syntax:
dataType nameOfTheArray [sizeOfTheArray];

int Arr[6];

example:
dataType nameOfTheArray [ ] = {elements of array };

int Arr [ ] = { 2, 3, 5, 4, 6, 7 };

Multidimensional array: It can be considered as an array of arrays. The most commonly used multidimensional array is 2-dimensional array. It stores the elements using 2 indices, which give the information, in which row and which column a particular element is stored. A 2D array is essentially a matrix.

Declaration:

char A[ 3 ] [ 2 ] ;

example:
include
include

using namespace std;
int main( ) {
int Arr[6]; // declaring Arr
Arr[ ] = { 2, 3, 5, 4, 6, 7 }; // Initializing Arr by storing some elements in it.
char A [ 3 ] [ 2 ]; // declaring a 2D array
A [ 3 ] [ 2 ] = { { ‘P’, ‘I’} , {‘O’, ‘M’ } , {‘G’, ‘D’} } ;

printf(“The third element of Arr is\n ”,  Arr[ 2 ]);
Enter fullscreen mode Exit fullscreen mode

for (int i = 0; i < 6 ; i ++ )
printf(“%d “, Arr[i]);
printf(“\n”);
printf(“All the elements of 2D array A[ ][ ] are : \n”);

for( int i = 0 ; i < 3; i++ ) {
for(int j= 0 ; j < 2 ; j++ ) {
printf(“%c “, A[i][j]);
}
printf(“\n”);
}
return 0;
}

String:

String is a sequence of characters that are treated as a single data item and terminated by a null character '\0'. Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.

example and syntax:
Declaring and Initializing a string variables:

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

char ch[3] = "hello";

char str[4];
str = "hello";

String Input and Output:
%s format specifier to read a string input from the terminal.

But scanf() function, terminates its input on the first white space it encounters.

edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.

The gets() function can also be used to read character string with white spaces.

example:

char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);

Top comments (0)