On Nov 8, 9:47*am, Rolf Magnus <ramag...@t-online.dewrote:

bintom wrote:

I teach C++ in schools in India. I don't have a good answer

when students ask me why arrays in C++ are numbered from 0

to n-1 for an array of n elements. I hope somebody can tell

me.

The reason why it's like that in C++: The array notion a[b] is

equivalent to *(a+b), where usually, a is the address of the

array's first element, and b is the index. So if you want the

first element, b must be 0. Basically, that's how all

computers do it. So if you have a language that starts at 1,

like e.g. Matlab does, the interpreter has to subtract 1 from

every index or alternatively leave the first element blank.

That's basically it. If you really want to make it clear,

however, without going into the nitty-gritty of transforming []

into * and +, consider "flatting" multidimensional arrays.

Given an array with dimension [10][10], for example, map the

indexes into those of an array [100]. With arrays based at 0,

it's simple 10*i+j. With arrays based at 1, you have to

subtract 1 from each index, then do the calcule, then add 1,

e.g. 10*(i-1)+j (with more dimensions, the difference becomes

even more apparent).

Generally, I'd rather ask why we tend to start counting at 1

instead of 0, but my guess is that this has historical reasons

(for quite a long time, there was no number 0).

Counting makes sense: if you have one book, you have one, and

not zero. It's indexing that doesn't, or rather ordinal

numbers in general.

--

James Kanze (GABI Software) email:ja*********@gmail.com

Conseils en informatique orientée objet/

Beratung in objektorientierter Datenverarbeitung

9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34