An array is a data structure used to store a collection of items in a continuous memory block. The memory allocated to the array is divided into multiple sequential slots and each slot can exactly store the information of an item. And each item stored in an array can be individually accessed by using the index (slot number).
Structure of an Array
Any program running on a computer requires storing and accessing of data temporarily. For example, if we write a program to add two numbers, we need to take input the two numbers to add and store them temporarily before adding them and displaying the result.
An array is one data structure which is used to store items of same type in a continuous memory block. It is similar to a row of houses, where each house is adjacent to atleast one house. Below is how the structure of an array looks like (source):
A continuous memory space (the area highlighted in blue) is allocated for Array
a. This continuous memory space is further divided into 5 slots and each slot can store an item in it. Here the size of the array becomes 5 (Since the memory is allocated to store a maximum of 5 items).
Each slot in the array is numbered starting from 0. So the first slot is identified by number
0, the second slot by number
1, the third slot by number
2 etc. So in order to access the third item stored in the array, we can use the corresponding slot’s number like this:
a. The number used to identify a slot is termed as the index of that slot. So for the second slot/item, the index is
1, for the third slot/item, the index is
When is an Array Necessary?
If the operation we need to do is simple and requires only a few variables, we can store the values in separate variables and perform the operation. For example, if we wish to add two numbers, we can initialize two numbers
b and create a formula
a+b to add the numbers.
But what if we need to add 10 numbers? sure we can initialize the numbers as
a3 .. to
a10. But what if the number of numbers to add change dynamically? or if the number of numbers to add is very large? This is where an array is really useful.
We can initialize an array to store any number of items we desire and then we can iterate / go through each slot in the array and access the item. For example, if we wish to store 100 items, we can initialize an array like
items and start filling each item starting from 0. So we fill
items next and finally
items. After filling all the items, we can iterate/visit each item and perform the operation like addition, finding the maximum element etc.