Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.for example:
we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier.Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.
For example: an array to contain 5 integer values of type int called billy could be represented like this:
Image7
where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [elements];
where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain. Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:
int billy [5];NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.
Initializing arrays:
When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }.
For example:
int billy [5] = { 16, 77, 40, 120,71 };
double billy[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}
No comments:
Post a Comment