Tuesday, October 27, 2020 09:27

Table of contents >> Arrays > Accessing the elements of arrays

Accessing the elements of arrays

As I was explaining in a previous post, arrays can be seen as a building (the array itself) with apartments (the elements of the array), each identified by an apartment number (the indices or the array elements). So, accessing the elements of arrays is done through their elements indices, just like finding an address is done through the apartment number inside a building.

Array indices start from 0 (not 1! this is a very common error for beginners!), they are consecutive numbers, and they end at the array’s elements count number – 1 (because indices start from 0, while the number of elements counts from 1).

By accessing the elements of arrays identified by an index, we can both read or assign a value, which means that the elements of the arrays can be treated as variables.

This is how we read and write values, by accessing the elements of arrays:

To better understand the structure of an array, this is how myArray could be illustrated:

accessing the elements of arrays

Because our array is of type int, its elements are not initialized as null, but with the default value of 0.

Arrays work hand-in-hand with loops. For instance, this is a quick way of populating the items of an array, or displaying all the elements of an array, by using a for loop and a property of arrays called Length (of which we will learn later):

The Length property of an array gives us an integer number representing the number of elements in that array (and it starts from 1, not 0!). So, in our case, arr.Length is 5, because we declared an array with 5 elements.

You should be aware that trying to access an element of an array using an index that is outside the range of indices for that array will cause what we call an exception of type IndexOutOfRangeException. For instance:

The above code will generate an out of range exception, because we declared an array of a single element, and as we already know, array indexes start from 0. This means that our single element array resides at the location identified by index 0, and trying to access the location with index 1 will generate an error, because there is no index 1 in an array with a single element.

Another thing you should be aware of is that you cannot display an array at console, directly. So, when you will try this:

do not expect to actually have the values of that array displayed on the console. Instead, you will get this:

printing arrays incorrectly

If you want to print the elements of an array, you need to cycle through all of its elements using a loop of some sort, and display each individual item. We will present this in the next lesson.

The concepts explained in this lesson are also shown visually as part of the following video:

Comments

comments

Tags: , ,

Leave a Reply



Do NOT follow this link or you will be banned from the site!