Array
Array
Array is a linear data structure that stores a collection of items of same data
type in contiguous memory locations. Each item in an array is indexed
starting with 0. We can directly access an array element by using its index
value.
Basic terminologies of Array
• Array Index: In an array, elements are identified by their indexes.
Array index starts from 0.
• Array element: Elements are items stored in an array and can be
accessed by their index.
• Array Length: The length of an array is determined by the number
of elements it can contain.
Memory representation of Array
In an array, all the elements are stored in contiguous memory locations. So,
if we initialize an array, the elements will be allocated sequentially in
memory. This allows for efficient access and manipulation of elements.
Declaration of Array
Arrays can be declared in various ways in different languages.
Need or
Applications of Array Data Structures
• Array is a fundamental data structure and many other data
structure are implemented using this. Implementing data structures
such as stacks and queues
• Representing data in tables and matrices
• Creating dynamic data structures such as Hash Tables and Graph.
• When compared to other data structures, arrays have the
advantages like random access (we can quickly access i-th item)
and cache friendliness (all items are stored at contiguous location)
Types of Arrays
Arrays can be classified in two ways:
• On the basis of Size
• On the basis of Dimensions
#include<vector>
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(arr[0]);
// Traversing over arr[]
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
2. Insertion in Array:
We can insert one or multiple elements at any position in the array. Below
is the implementation of Insertion in Array in C++ languages:
arr[pos] = x;
}
3. Deletion in Array:
We can delete an element at any index in an array. Below is the
implementation of Deletion of element in an array:
if (pos == -1) {
cout << "Element not found";
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}