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.



Similar Reads

How Does Google Map Works?
Google Maps is a unique web-based mapping service brought to you by the tech giant, Google. It offers satellite imagery, aerial photography, street maps, 360° panoramic views of streets, real-time traffic conditions, and route planning for traveling by foot, car, bicycle, or public transportation. A short history of Google maps: Google Maps was fir
10 min read
Understanding Efficient Spatial Indexing
In this article, we will be understanding Efficient Spatial Indexing. Efficient spatial indexing is a critical component of data structures and databases. It deals with organizing and accessing spatial data, and spatial data consists of objects with geographic or geometric coordinates such as points, lines, and polygons and spatial index structures
44 min read
Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
Give an integer array arr[] consisting of elements from the set {0, 1}. The task is to print the number of ways the array can be divided into sub-arrays such that each sub-array contains exactly one 1. Examples: Input: arr[] = {1, 0, 1, 0, 1} Output: 4 Below are the possible ways: {1, 0}, {1, 0}, {1}{1}, {0, 1, 0}, {1}{1, 0}, {1}, {0, 1}{1}, {0, 1}
6 min read
Maximize the size of array by deleting exactly k sub-arrays to make array prime
Given an array arr[] of N positive integers and a non-negative integer K. The task is to delete exactly K sub-arrays from the array such that all the remaining elements of the array are prime and the size of the remaining array is maximum possible. Examples: Input: arr[] = {2, 4, 2, 2, 4, 2, 4, 2}, k = 2 Output: 4 Delete the subarrays arr[1] and ar
10 min read
Pair of arrays with equal sum after removing exactly one element from each
Given K arrays of different size. The task is to check if there exist any two arrays which have the same sum of elements after removing exactly one element from each of them. (Any element can be removed, but exactly one has to be removed). Print the indices of the array and the index of the removed elements if such pairs exist. If there are multipl
10 min read
Divide array into two arrays which does not contain any pair with sum K
Given an array arr[] consisting of N non-negative distinct integers and an integer K, the task is to distribute the array in two arrays such that both the arrays does not contain a pair with sum K. Examples: Input: arr[] = {1, 0, 2, 3, 4, 7, 8, 9}, K = 4Output: 3, 2, 4, 7, 8, 9 0, 1 Explanation: Pairs (1, 3) and (0, 4) from the given array cannot b
6 min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Merge k sorted arrays | Set 2 (Different Sized Arrays)
Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ;Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ;Output: 1 2 3 4 6 20 We have discussed a solution that works for all arrays of the same size in Merge k sorted a
7 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Count of possible unique arrays after swapping elements at same index of given Arrays
Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[] = {1, 2, 3, 4}, arr2[] = {2, 1, 4, 3}, N = 4Outpu
9 min read
Practice Tags :