Introduction to Arrays
Arrays are the linear data structures that are used to store similar data in contiguous memory locations. An array has two prominent properties.
- An array can store only similar data.By similar data type we mean that if you have created an array to store roll numbers of students you cannot store names in it. Different array elements cannot have different data types.
- The elements of an array can be stored only in contiguous memory locations.
Array declaration and storage is possible in all programming languages. While declaring an array you have to specify the number of elements you want to store in the array. You cannot store more than the declared number of elements in an array. For example if you declare an array of size 10, you can store maximum 10 elements. Of course, you can store lesser number of elements than the maximum i.e. 10.
Accessing Array Elements
The elements stored can be accessed by the index or subscript of the elements. The first element has index 0 and the last element has index value 1 less than the size of the array.
The first element 5 is stored at the location identified by index 0. The last element 87 is stored at the location identified by index 9. The size of the array is 10, the index of the last element is 1 less than size i.e. 10-1=9.
Each element is identified by an index, called a subscript in some programming languages. Arrays are usually referred by name. Array elements are accessed by using the index of the element in square parenthesis after the array name. In the above example ARRAY is element 10 and ARRAY is element 2. The variable declared as an array contains address of the memory location where the first element is stored.
Array element can be accessed, inserted or removed by specifying its position (number of elements preceding it)
Advantages of using arrays
- Arrays are stored in contiguous memory and each element is identified with its index. So elements can be easily accessing elements using the positional value called index. The location of element can be calculated by sung base address or address of first element.
- Array are contiguous so all operations can be performed with high efficiency.
- Array are easy understand and easy to implement in a programming language.