Arrays

Array stores multiple values of identical type.

Array size (values count) is set during initialization.

Initialization

There are couple of ways to initialize array:

Empty array

In this case, we declare an array which can contain 10 integer numbers.

Initial values

In this example an array of 3 string values is created.

Defining array size via constant

Notice that array's size cannot be set through variable. It needs to be a constant.

Size

Size is the count of elements in array.

It's accessed via the sizeof function.

Output:

Accessing values

Array's values are accessed via indexes starting from 0.

If we declare the following array:

It's elements are:

array-indexing

So if we type the following line:

It will print:

Index out of Bounds

Accessing index outside of the array results in unexpected behaviour.

Let's have an array with 4 elements. If we access the 4th or higher index, the behaviour of the program is uncertain.

Such example is:

Printing All Elements

Let's have an example in which all elements of array are printed.

Output:

For loop is a convenient way to access all elements since it can provide numbers from 0 to array's count.

Accessing empty element

If not specified, elements hold default values.

It depends on their type (int, string, double etc...).

The most common default value is 0 for numeric types or "" for strings.

The following example prints element with set and unset value:

Output:

Inserting Elements

Elements can be inserted by specifying index and value.

Let's have a program which fills array with values:

Wrong type insertion

If we define an integer array but try to insert other type of value (like string), it will result in exception:

Such example is:

Calculating Average

To do that we need to find the sum of all elements and divide it to their count:

Output: