type name [elements];
where type is a valid type(such as int, float), the name is a valid identifier and the element field which is always enclosed in square brackets([]) specifies the length of an array in terms of the number of elements.
Therefore the value array with 5 elements of type int can be written as follows:
int value [5];
Note that the element field with square brackets representing the number of elements in the array must be a constant expression since arrays are blocks of memory whose size must be determined at compile time, before the program runs.
Initializing Arrays
By default, regular arrays of local scope(for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.
But the elements in the array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example
int values [5] = {1, 2, 3, 4, 5};
The number of values between braces {} shall not be greater than the number of elements in the array.
Arrays can also be created without elements and that the elements can be added later. The code below create an array of 5 length but without element. This is called an empty array:
int val [5] = { };
Accessing the values of an Array
The values of any element in the array can be accessed just like the value of a regular variable of the same type. Below is the syntax for that:
name[index];
Following the previous example in which value had 5 elements and each of those element was of type int, we can refer to each of the elements as follows:
value[0];
value[1];
value[2];
value[3];
value[4];
For example: value[0] stores integer 1.
Comments (0)