Open In App

How exactly does indexing works in Arrays?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

Base 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads