Why Array Index's Start With 0️ ?🤔

Suhail Roushan 🚀
3 min readOct 2, 2022

--

Why Array Index’s Start With 0️ ?

Lets take a simple array []

Where arr is a variable name

The Above Array Having 4 Elements Which are 10,20,30,40

Now Lets Think Why arr[0] is getting the first element ??

Points you should know before knowing it

An array is essentially a pointer.

What does it mean that an array is a pointer?

It means that it stores a memory address.

Instead of storing the value, it stores the location of that value.

Let’s understand this with an example -

⇒ Assume that 1st element of the array is pointed at location 100.

⇒ Also, consider the indexing starts from 1 not from 0.

Let’s find the location of the 1st element with the help of index (remember the location of 1st element is 100)

Example 1:

In the Above the array

Table 1.1
arr[0] = 100 (Address)
arr[1] = 104 (Address)
arr[2] = 108 (Address)
arr[3] = 112 (Address)

We are assuming the address are starting from 100 and each one is increment by 4 bytes

Size of the Array is 4 Bytes in JavaScript .

So it has been increment by 4 bytes

100 => 104 => 106 => 108 => 110 => 112

Position = arr[n]

Formula of arr[n] = base + (index)*bytes

Base = starting address of a array which we assume which is 100

index = now we took that array index starting from 1

bytes = In JavaScript array takes 4 bytes

Table 1.2
arr[0] = 100+(1*4)
= 100+4
= 104
But arr[0] should be 100 from Table 1.1

If array starts with 0

Table 1.3
arr[0] = 100+(0*4)
= 100+0
= 100
arr[0] should be 100 which is same Equal to Table 1.1

Example 2:

// Program to take 5 values from the user and store them in an array// Print the elements stored in the array
#include
<stdio.h>
int main()
{
int mark[5] = {19, 10, 8, 17, 9};
printf("Displaying integers: ");
// printing elements of an array
for
(int i = 0; i < 5; ++i){
printf("%d\n", mark[i]);
}
//Output :- 19,10,8,17,9
for (int j = 0; j < 5; ++j){
printf("%d\n", *(mark + j));
}
//Output :- 19,10,8,17,9return 0;
}

In the Above C Program

mark[i] is equal to *(mark( + j))

mark[i] = *(mark( + j))

Where *(mark( + j)) is

  • * is pointer in C Language
mark = base addressj = (index*bytes)(mark( + j)) = base + (index *  bytes)= 100+(0*4)= 100+0= 100 which is same as again from Table 1.1

The 20 Programming Languages where index’s start from 1 (NOT 0) are:

ALGOL 98APLAWKCFMLCOBOLFortranFoxProJuliaLingoLuaMathematicaMatlabPL/IRPGRRingSassSmalltalkWolfram LanguageXPath/ XQuery

--

--

Suhail Roushan 🚀
Suhail Roushan 🚀

Written by Suhail Roushan 🚀

Suhail Roushan | Software Engineer @The Hacking School | Instructor @CFI Foundation | Full Stack, DevOps & Automation Enthusiast 🌍 suhailroushan.com

No responses yet