Arrays
- Shreyas Naphad
- May 8, 2024
- 2 min read
Updated: May 25, 2024
In this article, we will be understanding the concept of an array. So before understanding the technical aspect let us understand the array with an easy real-life example.
Imagine arrays as boxes in a mall. Each box can contain items such as toys, books, or clothes.
Similar to this, arrays allow us to store and organize items so that we can find it easily whenever we need it.
Here is an example:
Let's say we have five food items that we want to store in a box. This box will contain these food items. So for this, we can use an array where all food items will be stored together. So an array can act like a box containing our food items.
Food_items = ["cakes", "cookies", "fruits", "chocolates", "popcorns"]
Now, if we want to get cookies, we know that it is the 2nd item in the box. It is important to know that arrays start from 0 and not 1 and hence the index of cookies is 1.
cookies = Food_items[1] // Counting starts from 0
So the formal definition of an array is that an array is a linear data structure used to store a collection of elements that are of the same data type and are stored in contiguous memory locations
Types of Arrays:
1) One-dimensional Arrays: These arrays consist of a single row of elements. These are like a list of items that we discussed above, where each item can be accessed using its index. For example, an array of integers [1, 2, 3, 4, 5] is a one-dimensional array.
2) Multi-dimensional Arrays: Here the arrays can have multiple dimensions that will be in form of a matrix. For example, a 2D array can be visualized as a table with rows and columns, where each element is accessed using two indices one for row and second for column.
3) Dynamic Arrays: The significance of dynamic arrays is that they can grow or shrink in size as needed unlike the above two types of arrays. This flexibility comes in handy when the number of elements to be stored is unknown beforehand or changes over time.
Key Points About Arrays:
1) Contiguous Memory Allocation: When an array is created, the elements are stored in contiguous memory locations which makes accessing them is fast and efficient.
2) Fixed Size: Arrays have a fixed size (except dynamic). This means we must specify the size of the array while creating the array.
3) Zero-based Indexing: The indexing of elements in an array starts from 0 and not 1.
4) Random Access: Arrays have the ability of random access, which means we can access any element in the array with the help of its index.
Commentaires