Ch4 Arrays Lec1
Ch4 Arrays Lec1
Ch4 Arrays Lec1
BASIC ARRAYS
Variables and Multiple Values
• A variable is capable of storing only one value
at a time.
• Each of the variable definitions below cause
only enough memory to be reserved to hold
one value of the specified data type.
Example
A short uses 2 bytes of memory, so the age array would occupy 12 bytes.
Accessing Array Elements
Even though an entire array has only one name, the elements may be
accessed and used as individual variables.
This is possible because each element is assigned a number known as a
subscript
. A subscript is used as an index to pinpoint a specific element within an
array.
E.g See the subscripts below in an array of size 3
prices[0]= 56.981;
Note: The expression prices[0] is pronounced “prices sub zero”
e.g. prices sub 1 is assigned 23.124
prices[0] prices[1] prices[2]
56.981 ? ?
These values are stored in the array elements in the order they
appear in the list. (The first value, 31, is stored in days[0], the
second value, 28, is stored in days[1], and so forth).
Partial Array Initialization
An initialization list cannot have more values than the array has elements, but
it may have fewer values than there are elements.
That is, C++ does not require a value for every element. It’s possible to only
initialize part of an array, such as
int numbers[7] = {1, 2, 4, 8};
Implicit Array Sizing
It’s possible to define an array without specifying its size, as long as you
provide an initialization list that includes a value for every element.
C++ automatically makes the array large enough to hold all the
initialization values.
For example, the following definition creates an array with five elements:
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};