An array is a linear data structure which stores collection of data in a contagious memory location. The idea is to store the collection of the same type of data. this makes it easier to calculate the position of each item by simply adding an offset to a base value.
In the above image of an array, we can identify each element by its index.
we can declare an array by specifying the types of its element.
type [] arrayname;
Types of Arrays
- single dimensional arrays
- Multidimensional arrays
Single Dimensional Arrays
A single dimensional array can be declared in the following way.
int[] array = new int[5];
this array will contain the element from array[0] to array[4].the new operator will initialize
each element of this array with zero.
An array which contains string value can be declared the same way.
string[] array = new string[6];
Array Initialization
we can also initialize an array while declaration. For example
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
In the same way, we can also initialize a string array.
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
Multidimensional Arrays
Arrays can have more than one dimension. For example.
int[,] array = new int[6, 3];
the above declaration creates a two-dimensional array of six rows and three columns.
The following declaration creates an array of three dimensions, 6, 3, and 2.
int[, ,] array1 = new int[6, 3, 2];
Array Initialization
we can initialize the array upon declaration.For example
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
Happy Programmig :)
Comments
Post a Comment