Array Basics
• An array is a block of contiguous
memory locations to hold values of
a single specified type.
• Arrays can hold values of ANY type
• In C++, arrays are 0-based. This
means that the first element has
index 0.
Declaring an Array
• To declare an array, use the following
structure
type VariableName [ SIZE ];
Example:
int myArray[5];
declares an array named myArray
that can hold 5 integers with indices
0, 1, 2, 3, and 4.
Declaring an Array
• Note: We are using static arrays.
IE the size must be set when the
array is declared, and can not
change during the course of the
program.
• Use constant variables for the
array’s size so that modifications to
the size can be made in one place.
Using an Array
• In C++, the name of the array
refers to the address of the first
element in the array.
• In order to access an element in
the array, follow the name of the
array with square brackets
containing the element’s index.
Using an Array
In our example, int myArray[5];
declares an array of 5 integers.
14 0 0 0 0
Using an Array
• You can leave out the size of the
array when using a list to initialize
the array in the declaration. The
array’s size will be the number of
values in the initialization list.
Example:
int Array[] = {14, 3, 6, 9, 2};
14 3 6 9 2
Using an Array
• To read values into a non-character
array, use a counter controlled loop
to move through the array indices.
Example:
for( int i = 0; i < 5; ++i )
{
cout << “Enter next number”;
cin >> myArray[ i ];
}
Using an Array
• To output the values in a non-
character array, use a counter
controlled loop to move through
the array indices.
Example:
for ( int i = 0; i < 5; ++i)
{
cout << myArray[ i ] << “ “;
}
Using an Array
• Common Error: Overstepping the
bounds of an array.
• Your compiler will not produce an
error if an index is used outside of
the 0 to size – 1 range.
• Invalid indices are used as any
other, moving the specified offset
from the first element in the array.
Using an Array
• Overstepping an array’s bounds
can attempt to modify values in
memory locations being used by
other variables or programs.
Using an Array
Example:
int myArray[] = {1,2,3,4,5};
for ( int i = 0; i <=5; ++i )
{
myArray[i] *= 2;
}
Before 1 2 3 4 5
After 2 4 6 8 10 ???
Passing Arrays to Functions