Why array index starts from zero ?
Last Updated :
28 May, 2024
Prerequisite : Pointers in C/C++
THERE CAN BE MANY REASONS, BUT HERE ARE TWO REASONS:
Reason 1 :
Consider int arr[100]. The answer lies in the fact how the compiler interprets arr[i] ( 0<=i<100).
arr[i] is interpreted as *(arr + i). Now, arr is the address of the array or address of 0th index element of the array. So, address of next element in the array is arr + 1 (because elements in the array are stored in consecutive memory locations), further address of next location is arr + 2 and so on. Going with the above arguments, arr + i mean the address at i distance away from the starting element of the array. Therefore, going by this definition, i will be zero for the starting element of the array because the starting element is at 0 distance away from the starting element of the array. To fit this definition of arr[i], indexing of array starts from 0.
CPP
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4 };
// Below two statements mean same thing
cout << *(arr + 1) << " ";
cout << arr[1] << " ";
return 0;
}
Java
public class Main {
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4 };
System.out.print(arr[1] + " ");
System.out.print(arr[1] + " ");
}
}
// This code is contributed by Shivam Gupta
Python
# code
print("GFG")
arr = [1, 2, 3, 4]
# Below two statements mean the same thing
print(arr[1], end=" ")
print(arr[1], end=" ")
JavaScript
// Main function
function main() {
const arr = [1, 2, 3, 4];
// Accessing the second element of the array using array subscript notation
console.log(arr[1] + " ");
// Accessing the second element of the array using pointer arithmetic (not valid in JavaScript)
console.log(arr[1] + " ");
}
// Call the main function to execute the example usage
main();
The conclusion is, we need random access in the array. To provide random access, compilers use pointer arithmetic to reach i-th element.
Reason 2 :
Modern languages, especially C++ use row-major ordering for storing two-dimensional arrays.
Let us assume a 2D array and write a row-major formula with two different approaches:
- array indices starting from 1
- array indices starting from 0
let the 2D array be arr[m][n] of type int
let &arr be "address"
case 1 ( array indices start from 1 ) :
&( arr[i][j] ) = address + [ ( i-1 )*n + ( j-1 ) ]*( sizeof(int) ) ] so here we are performing 6 operations
case 2 ( array indices start from 0 ) :
&( arr[i][j] ) = address + [ ( i )*n + ( j ) ]*( sizeof(int) ) ] and here we are performing only 4 operations
So we see here that we are performing 2 less operations when we store 2D arrays and obtaining an element's address. This looks like it doesn't make sense but it does! While handling with huge size data this may improved performance and speed. case 1 may look user-friendly but case 2 is more efficient. That's why most languages like C++, PYTHON, JAVA use arrays starting with index 0 and rarely languages like Lua arrays starting with index 1.
Similar Reads
How exactly does indexing works in Arrays? 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
5 min read
Indexed Sequential Search In this searching method, first of all, an index file is created, that contains some specific group or division of required record when the index is obtained, then the partial indexing takes less time cause it is located in a specified group. Note: When the user makes a request for specific records
7 min read
Leaf starting point in a Binary Heap data structure Binary Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). In other words, we can say that it's an almost complete binary tree. A Binary heap is typically represented as array. If we take a closer look, we can
2 min read
Python String index() Method The index() method in Python is used to find the position of a specified substring within a given string. It is similar to the find() method but raises a ValueError if the substring is not found, while find() returns -1. This can be helpful when we want to ensure that the substring exists in the str
2 min read
Java String indexOf() Method In Java, the String indexOf() method returns the position of the first occurrence of the specified character or string in a specified string. In this article, we will learn various ways to use indexOf() in Java.Example:Below is the simplest way that returns the index of the first occurrence of a spe
3 min read