Array
Arrays
Array
Consecutive group of memory locations
All of which have the same type
Index
Position number used to refer to a specific location/element
Also called subscript
Place in square brackets
Must be positive integer or integer expression
First element has index zero, last element has index n-1
Properties of an array
Homogeneous
Contiguous
Have random access to any element
Ordered (numbered from 0 to n-1)
Number of elements does not change - be a constant when
declared
Declaring Arrays
When declaring arrays, specify
Name
Type of array
Number of elements
arrayType arrayName[ numberOfElements ];
Examples:
int c[ 10 ];
float myArray[ 3284 ];
Declaring multiple arrays of same type
Format similar to regular variables
Example:
int b[ 100 ], x[ 27 ];
4
Examples Using Arrays
Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
All elements 0
If too many a syntax error is produced
If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
5
Array of 12 elements
Arrays (Cont.)
Examine array c in the figure
c is the array name
c has 12 elements ( c[0], c[1], … c[11] )
The value of c[0] is –45
Declaration of an Array
The index is also called the subscript
In C++, the first array element always has subscript 0, the
second array element has subscript 1, etc.
The base address of an array is its beginning address in
memory
8
Using a named constant
It is very common to use a named constant to set the size of
an array
E.g.
const int SIZE = 15;
int arr[SIZE];
Useful because it can be used to control loops throughout
program
Easy to change if size of array needs to be changed
It is important to note the difference between the “seventh
element of the array” and “array element 7.”
Array subscripts begin at 0, so the “seventh element of the
array” has a subscript of 6, while “array element 7” has a
subscript of 7 and is actually the eighth element of the array.
Unfortunately, this distinction frequently is a source of off-by-
one errors.
To avoid such errors, we refer to specific array elements
explicitly by their array name and subscript number (e.g., c[ 6 ]
or c[ 7 ]).
Solution to problem
int counter = 0, n[5], total average = total / 5;
= 0; ct= 0;
float average; while (ct < 5)
while (counter < 5) {
if (n[ct] >
{
average)
cout << "enter a number ";
cout << n[ct];
cin >> n[counter];
ct = ct + 1;
total = total + n[counter];
}
counter = counter + 1;
}
Initializing Array
Initializing an array in a declaration with an initializer list
Initializer list
Items enclosed in braces ({})
Items in list separated by commas
Example
int n[] = { 10, 20, 30, 40, 50 };
o Because array size is omitted in the declaration, the
compiler determines the size of the array based on the size
of the initializer list
o Creates a five-element array
o Index values are 0, 1, 2, 3, 4
o Initialized to values 10, 20, 30, 40, 50, respectively
Initializing Array
If fewer initializers than elements in the array
Remaining elements are initialized to zero
Example
int n[ 10 ] = { 0 };
o Explicitly initializes first element to zero
o Implicitly initializes remaining nine elements to zero
If more initializers than elements in the array
Compilation error
Initialization of arrays
int a[] = {1, 2, 9, 10}; // has 4 elements
int a[5] = {2, 5, 4, 1, -2, 5}; // error!
int a[5] = {2, 3}; // rest are zero
int a[5] = {0}; // all are zero
can use it with char, float, even bool
Assigning Values to
Individual Array Elements
float temps[5];
int m = 4; // Allocates memory
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
7000 7004 7008 7012 7016
99.4 ? 98.6 101.2 50.6
temps[0] temps[1] temps[2] temps[3] temps[4]
15
What values are assigned?
float temps[5]; // Allocates memory
int m;
for (m = 0; m < 5; m++)
{
temps[m] = 100.0 + m * 0.2 ;
}
7000 7004 7008 7012 7016
? ? ? ? ?
temps[0] temps[1] temps[2] temps[3] temps[4]
16
Now what values are printed?
float temps[5]; // Allocates memory
int m;
.....
for (m = 4; m >= 0; m--)
{
cout << temps[m] << endl;
}
7000 7004 7008 7012 7016
100.0 100.2 100.4 100.6 100.8
temps[0] temps[1] temps[2] temps[3] temps[4]
17
Indexes
Subscripts can be constants or variables or expressions
If i is 5, a[i-1] refers to a[4] and a[i*2] refers to a[10]
You can use i as a subscript at one point in the program and j
as a subscript for the same array later - only the value of the
variable matters
Variable Subscripts
float temps[5]; // Allocates memory
int m = 3;
......
What is temps[m + 1] ?
What is temps[m] + 1 ?
7000 7004 7008 7012 7016
100.0 100.2 100.4 100.6 100.8
temps[0] temps[1] temps[2] temps[3] temps[4]
19
Selection sort - 1-d array
Algorithm for the sort
1. find the maximum in the list
2. put it in the highest numbered element by swapping it
with the data that was at that location
3. repeat 1 and 2 for shorter unsorted list - not including
highest numbered location
4. repeat 1-3 until list goes down to one
Find the maximum in the list
// n is number of elements
max = a[0]; // value of largest element //
seen so far
for (i = 1; i < n; i++) // note start at 1, not 0
if (max < a[i])
max = a[i];
// now max is value of largest element in list
Find the location of the max
max = 0; // max is now location of the max
for (i = 1; i < n; i++)
if (a[max] < a[i])
max = i;
Swap with highest numbered
element at right end of list is numbered n-1
temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
Find next largest element and swap
max = 0;
for (i = 1; i < n-1; i++) // note n-1, not n
{
if (a[max] < a[i])
max = i;
}
temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
put a loop around the general code to
repeat for n-1 passes
for (pass = n-1; pass >= 0; pass --)
{ max = 0;
for (i = 1; i <= pass; i++) {
if (a[max] < a[i])
max = i;
}
temp = a[max];
a[max] = a[pass];
a[pass] = temp;
}
Multidimensional Array
Multidimensional arrays with two dimensions
Called two dimensional or 2-D arrays
Represent tables of values with rows and columns
Elements referenced with two subscripts ([x][y])
In general, an array with m rows and n columns is called an m-
by-n array
E.g.
int a[5][4]; // row then column
twenty elements, numbered from [0][0] to [4][3]
Multidimensional arrays can have more than two dimensions
Two-Dimensional Array
A two-dimensional array is a collection of components,
all of the same type, structured in two dimensions,
(referred to as rows and columns)
Individual components are accessed by a pair of indexes
representing the component’s position in each dimension
DataType ArrayName[ConstIntExpr][ConstIntExpr]...;
27
Processing a 2-d array by rows
finding the total for the first row
for (i = 0; i < 5; i++)
total = total + a[0][i];
finding the total for the second row
for (i = 0; i < 5; i++)
total = total + a[1][i];
Processing a 2-d array by rows
Total for ALL elements by adding first row, then
second row, etc.
for (i = 0; i < 5; i++)
for (j = 0; j < 4; j++)
total = total + a[i][j];
Processing a 2-d array by columns
Total for ALL elements by adding first column,
second column, etc.
for (j = 0; j < 4; j++)
for (i = 0; i < 5; i++)
total = total + a[i][j];
End of Array []
31