Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does array-size declaration use "1" as the first index?

Tags:

java

arrays

c#

Something that I noticed about C#/Java is this seemingly (to me at the moment) inconsistent issue with array size declaration and the default first-index of array sizes.

When working with arrays, say you want to create a new integer array size 3, it would look like this:

int[] newArray = new int[3] {1, 2, 3};

Totally find and readable... Right?

The standard with programming languages seem to dictate that the "first" index is 0.

Using that logic, if I am interested in creating an array the size 3, I should really be writing this:

int[] newArray = new int[2] {1, 2, 3};

Wait a minute.. VS is throwing an error, saying an array initialize of length 2 is expected.

So there's an inconsistency with the first index in looping through an array and the array-size declaration? The former uses a 0-th based index, and the second a 1-th index.

It's not game-breaking/changing in any form or way, but I'm genuinely curious why there's a discrepancy here, or hell, if this is even an issue at all (like I say, it's not game-breaking in any way, but I'm curious as to why it's done this way).

I can at the moment think of reasons why 1-th based index would be used:

In a for-loop you would use < newArray.Length as opposed to < newArray.Length - 1 or < newArray.Length.

Working with Lists for awhile and then coming back to size-needs-to-be-declared-arrays caught me a bit off-guard.

like image 982
theGreenCabbage Avatar asked Nov 27 '22 21:11

theGreenCabbage


1 Answers

Because you are declaring the array with the number of elements it will contain.

I am unsure how that is inconsistent.

How many times do you have to saw to cut a log in 3 pieces? Hint: not 3 times.

Also note how in your post title you incorrectly refer to the array size declaration as 'index'.

like image 183
Wim Avatar answered Nov 30 '22 11:11

Wim