An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as in the data type must be the same for all elements.
Arrays are
widely used data type in ‘C’ language. It is a collection of elements of
similar data type. These similar elements could be of all integers, all floats
or all characters.
An array of
character is called as string whereas and array of integer or float is simply
called as an array.
So array may be
defined as a group of elements that share a common name and that are defined by
position or index. The elements of an arrays are store in sequential order in
memory.
There are mainly
two types of Arrays are used:
●
One
dimensional Array
●
Multidimensional
Array
1. One dimensional Array
The syntax to declare single dimension array is:
datatype arrayname[size];
The declaration
int a[10];
declares an
array, named a, consisting of ten elements, each of type int.
We can represent the array a above with a picture like this:
The first
element of the array is a[0], the second element is a[1], etc.
For example:
a[0] = 10;
a[1] = 20;
Array Initialization
It is possible to initialize some or all elements of an array when the array is defined.
The syntax looks
like this:
int a[10] = {0, 1, 2,
3, 4, 5, 6, 7, 8, 9};
The list of values, enclosed in braces {}, separated by commas, provides the initial values for successive elements of the array.
For example, it's common to loop over all elements of an array:
int i;
for(i = 0; i < 10; i
= i + 1)
a[i] = 0;
This loop sets all ten elements of the array a to 0.
To set all of the elements of an array to some value, you must do so one by one, as in the loop example above. To copy the contents of one array to another, you must again do so one by one:
int b[10];
for(i = 0; i < 10; i
= i + 1)
b[i] = a[i];
2. Multidimensional Array
The syntax to declare a double dimension array is:
datatype arrayname[rowsize][columnsize];
The declaration of an array of arrays looks like this:
int a[5][7];
Initialization of Array:
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
For accessing a two dimensional array a pair of nested loop is used as follows:
for (i = 0; i < 5; i = i + 1)
{
for (j = 0; j
< 7; j = j + 1)
printf
("%d\t", a2[i][j]);
printf
("\n");
}
No comments:
Post a Comment