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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read