Ranjith
Ranjith

Reputation: 33

what is the reason for mention array[0] to get first value?

what is the reson for mention the array[0] to get first the values in arrarys. Why we not use arrary[1] to get first values. if we use arrary[1] means easy to programmers but why we using array[0]

Upvotes: 1

Views: 108

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320631

In what programming language? There are programming languages where arrays are indexed from 1. There are programming languages where arrays are indexed from 0. There are programming languages where arrays are indexed from any user-defined value.

In lower-level languages you might see 0 used at the starting index simply because at hardware level the very first element of the array is located at byte-offset 0 from the beginning of the entire array in memory. This allows for a very simple and efficient formula for calculating byte-offsets for various array elements as. E.g. for i-th element of the array the byte-offset is i * element_size. Such simple calculations (e.g. multiplication by compile-time constant) can be implemented by a single machine instruction on the given hardware, which makes array access especially efficient.

Upvotes: 0

Patashu
Patashu

Reputation: 21783

The convention of using 0 as the first array index dates back to C. In C, Arrays as a concept were very tightly coupled to the underlying memory model - an array was literally a series of values in memory, starting at the address it was allocated at. And to get an address from this array, you would take its value as a pointer, increment a pointer value and see what's in memory at that place. Adding 0 to to this 'pointer' before dereferencing it gave you the first item in the array - so it was natural to use 0 first, otherwise every time you allocated an array you'd either 1) have to decrement 1 before every access or 2) waste a whole item space every allocation. It also had a third advantage - if your array had 256 entries in it, you could index it with a byte (which holds only 0 to 255), but if the array started at 1, 256 is not a valid value for a byte, so you would have to use a short.

Languages such as Java and C# and Javascript that inherit the syntax and thus model of thinking of C also use 0 indexed arrays for the same reason - consistency is a powerful thing.

Some languages, such as Lua, have the goal of being 'intuitively understandable' and start at 1, in contrast.

Upvotes: 2

Related Questions