How exactly does indexing works in Arrays?
Last Updated :
15 Feb, 2024
First, let's understand arrays, It is a collection of items stored at contiguous memory locations. The basic idea is to store multiple items of the same type together which can be accessed by index/key (a number).
The contiguous memory of declared size is allocated on heap/stack and then the address of the element is calculated mathematically during run-time as:-
element address = (base address) + (element index * size of a single element)
where,
- Base address: It is the address of the element at the index 0 or the location of the first element of the array in the memory.. The compiler knows this address as the memory location of the array.
- Element index: It is the sequential number (index/key) assigned to the element where the first element of the array is assigned 0. It can also be defined as the number of elements prior to that particular element in the array.
- Size of a single element: Elements in the array need to be of the same data type or object. The size of the single element is the number of bytes required in memory to store a single element of that kind.
For example:
Int type requires 4-bytes (32-bit)
char type requires a 1-byte (8-bit)
long type requires 8-byte (64-bit) etc.
Example of above implementation:
int arr[6] = {3, 4, 7, 9, 7, 1}
address of arr[0] (base address) = 0 x 61fe00
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0 x 61fe00 + ( 3 * 4) = 0 x 61fe0c
Here, size of a single element is 4-bytes as it is int- type array.
long long arr[6]={100, 12, 123, 899,124, 849}
address of arr[0] (base address) = 0x61fdf0
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0x61fdf0 + ( 3 * 8) = 0x61fe08
Here, size of a single element is 8-bytes as it is long - type array.
Note: Here addresses are of Hexadecimal form.
Let's see its implementation through a program to print the address of the array elements:
C++
// Program to show how indexing works
#include <iostream>
using namespace std;
int main() {
int arr[6] = {3,4,7,9,7,1};
cout << "Base address:- " << (&arr) << endl;
cout << "Element address at index 3:- " << (&arr[3]) << endl;
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {3, 4, 7, 9, 7, 1};
System.out.println("Base address:- " + (arr));
System.out.println("Element address at index 3:- " + (arr[3]));
}
}
//This code is contributed by Akash Jha
Python3
arr = [3, 4, 7, 9, 7, 1]
print("Base address:- ", arr)
print("Element address at index 3:- ", id(arr[3]))
#This code is contributed by Akash Jha
C#
using System;
class MainClass {
public static void Main (string[] args) {
// Array initialization
int[] arr = {3, 4, 7, 9, 7, 1};
// Printing the base address of the array
Console.WriteLine ("Base address:- " + arr.GetHashCode());
// Printing the address of the element at index 3
Console.WriteLine ("Element address at index 3:- " + arr[3].GetHashCode());
}
}
JavaScript
let arr = [3, 4, 7, 9, 7, 1];
console.log("Base address:- " + arr);
console.log("Element address at index 3:- " + (arr[3]));
//This code is contributed by Akash Jha
OutputBase address:- 0x7ffc64918c30
Element address at index 3:- 0x7ffc64918c3c
Time Complexity : O(1), since accessing array index require constant O(1) time.
Auxiliary Space : O(1), since no extra space has been used.
Python :
In Python, indexing in arrays works by assigning a numerical value to each element in the array, starting from zero for the first element and increasing by one for each subsequent element. To access a particular element in the array, you use the index number associated with that element.
For example, consider the following code:
Python
my_array = [10, 20, 30, 40, 50]
print(my_array[0]) # prints the first element (10)
print(my_array[2]) # prints the third element (30)
In this example, we define an array my_array that contains five elements. We then use indexing to access the first element (which has an index of 0) and the third element (which has an index of 2) and print their values to the console.
It's important to note that if you try to access an index that is outside the bounds of the array, you will get an "IndexError" exception. For example:
Python
print(my_array[5]) # raises an IndexError exception
This code will raise an "IndexError" exception because there is no element in my_array with an index of 5.
Additionally, you can use negative indices to access elements from the end of the array. For example:
Python
print(my_array[-1]) # prints the last element (50)
print(my_array[-2]) # prints the second-to-last element (40)
In this case, -1 corresponds to the last element in the array, -2 corresponds to the second-to-last element, and so on.
Similar Reads
How arrays works in TypeScript ?
Array in TypeScript is just similar to an array in other programming languages. The array contains homogeneous values means a collection of multiple values with different data types. TypeScript array is also fixed size, can not be resized once created. An array is a type of data structure that store
2 min read
How Array is stored in different programming languages?
The memory representation of an array mainly depends on various programming languages like C, C++, Java, Python, JavaScript, C#, and PHP. So we look at how an array is stored in several popular programming languages : How is Array stored in Memory in C and C++? In C and C++, arrays are stored as con
3 min read
Indexing Multi-dimensional arrays in Python using NumPy
In this article, we will cover the Indexing of Multi-dimensional arrays in Python using NumPy. NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific compu
3 min read
How HashTable Works Internally in Java?
Hashtable is a kind of Hash map but is synchronized. Hash map is nonâsynchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, Â the key/values pairs are stored in Hashtable. The Hash table does not allow null
12 min read
How to Find Index of Element in Array in MATLAB?
In MATLAB, the arrays are used to represent the information and data. You can use indexing to access the elements of the array. Â In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indi
4 min read
How to Insert a New Element in an Array in PHP ?
In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read
One Dimensional Arrays in C++
One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its posi
6 min read
One Dimensional Arrays in C
In C, an array is a collection of elements of the same type stored in contiguous memory locations. This organization allows efficient access to elements using their index. Arrays can also be of different types depending upon the direction/dimension they can store the elements. It can be 1D, 2D, 3D,
5 min read
How to find the Index of value in Numpy Array ?
In this article, we are going to find the index of the elements present in a Numpy array.Using where() Methodwhere() method is used to specify the index of a particular element specified in the condition.Syntax: numpy.where(condition[, x, y])Example 1: Get index positions of a given valueHere, we fi
5 min read
Inserting Elements in an Array - Array Operations
In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as:Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element at
2 min read