




Arrays Introduction
Array is a basic data structure used to store a list of elements. Each element is accessed by its index, starting from zero.
In this example, [10, 20, 30, 40, 50] are the array elements, and 0, 1, 2, 3, 4 are the respective index values.
Definition of an Array
An array is a linear data structure that stores elements in contiguous memory locations. Each element can be accessed directly using its index.
Arrays are ideal for situations where fast retrieval and processing of data is required.
Key Features of Arrays
1. Indexed Access
Each element in an array can be accessed using its index.
index starts from 0.
Consider the following array
:
- index of first element 10 is 0.
- index of second element 20 is 1.
- index of third element 30 is 2.
- index of fourth element 40 is 3.
- index of fifth element 50 is 4.
For example, array[2]
gives you the third element: 30.
2. Fixed or Dynamic Size
In some programming languages, arrays have a fixed size and cannot be resized. In others, like high-level scripting languages, Python, JavaScript, etc., arrays can grow or shrink dynamically as elements are added or removed.
Array with elements appended:
Consider the following array
:
Let us add two more elements, say 60 and 70, to this array
:
Or, if you remove the last two elements from the original array
, then the resulting array becomes the followign with size reduced by two.
3. Contiguous Memory Allocation
Arrays store elements in contiguous memory blocks, which allows fast access and better CPU cache performance. While this is handled internally, it’s a key reason arrays are fast and reliable.
4. Efficient Traversal
Since arrays use sequential memory and indexed access, traversing the array using loops is highly efficient. For example, looping from the first to the last index allows visiting every element once.
Common Use Cases of Arrays
1. Storing Lists of Data
Arrays are used for storing ordered collections of data such as numbers, characters, or objects. Some of the examples are tracking student grades, storing temperature readings, or listing items in a shopping cart.
2. Matrix Representations
Arrays can be used for representing matrices — grids of rows and columns.
3. Algorithm Design
Many core computer science algorithms rely on arrays due to their predictable structure and efficient access time. Sorting algorithms like Bubble Sort, Quick Sort, or Merge Sort use arrays as the fundamental data structure. Searching algorithms such as Linear Search or Binary Search also work directly with arrays.
4. Buffers and Queues
Arrays act as the underlying structure for many abstract data types such as stacks, queues, deques, and circular buffers.