Arrays:
Array is a collection of similar data type variables. They can be accessed using an index which generally starts from 0. There are two types of arrays which can store the data in a continuous memory allocations. They are single dimensional array and multi dimensional array.
single dimensional array:
single dimensional array is 1 dimensional array that stores elements in a linear sequential order. Syntax of declaring one dimensional array is as follows:
datatype arrayname[size of the array];
We can use this one dimensional array as follows
datatype arrayname[size of the array]={Elements of the array};
Let us try this with a simple example;
int array[ ]={2,3,4,5,6,7}; here array is the name of the array.
In the above example if we want to access 4th element we need to give array[3] to get the 4th element. This is because the sequential indexing starts with 0. similarly nth element can be accessed by array[n-1].
multidimensional array:
It is also called as matrix array. Most commonly used multi dimensional array is 2 dimensional array. It consists of two columns. It is also popularly known as arrays of arrays.It stores elements using 2 indices which gives the information in which row which column the element is placed. A 2D array is essentially a matrix.
declaration:
datatype arrayname[size of rows][size of columns];
example:
char arr[3][2];
here arr is a 2D array of character type. The array contains 3 rows and 2 columns. This array can store three words of length two. PI,OM,GD. These words can be stored as follows:
Here rows and columns start with 0 index. If you have to access D character, you can access it by arr[2][1].
Strings:
A string is sequence of characters. Sting is an array of character data type. An instance of a string is called a string literal, which are enclosed in double quotes("").
Declaration:
char string_name[size of array];
char str[5];
string can be initialized as a normal array but with the characters.
let us try this with an example:
char string[5]={'h','a','i'}
We can initialize this string in another way:
char str[]="hello";

here End of the string can be represented by the null character. In the above example str is a string which has an instance hello. Inspite of n characters the size of the string has n+1 characters because of the null string. The compiler automatically adds the null character at the end of the string. size of the string is always greater than the size of array.



No comments:
Post a Comment