Array stores multiple values of identical type.
Array size (values count) is set during initialization.
There are couple of ways to initialize array:
In this case, we declare an array which can contain 10 integer numbers.
In this example an array of 3 string values is created.
Notice that array's size cannot be set through variable. It needs to be a constant.
Size is the count of elements in array.
It's accessed via the sizeof
function.
Output:
Array's values are accessed via indexes starting from 0.
If we declare the following array:
It's elements are:
So if we type the following line:
It will print:
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:
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.
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:
Elements can be inserted by specifying index and value.
Let's have a program which fills array with values:
If we define an integer array but try to insert other type of value (like string), it will result in exception:
Such example is:
To do that we need to find the sum of all elements and divide it to their count:
Output: