Array
Array
Array
Chapter 7
Arrays
Objectives
In this chapter, you will learn about:
One-Dimensional Arrays
Array Initialization
Arrays as Arguments
Two-Dimensional Arrays
Common Programming Errors
Searching and Sorting Methods
One-Dimensional Arrays
One-dimensional array (single-dimension array or
vector): a list of related values
All items in list have same data type
All list members stored using single group name
Syntax
dataType arrayName[numberOfItems]
Common programming practice requires defining
number of array items as a constant before declaring
the array
10
11
12
Example 2
cout << "The value of element " << i << " is
" << grade[i];
Example 3
const int NUMELS = 20;
for (int k = 5; k < NUMELS; k++)
cout << k << " " << amount[k];
13
14
a
a
a
a
a
grade[0]
grade[1]
grade[2]
grade[3]
grade[4]
grade:
grade:
grade:
grade:
grade:
is
is
is
is
is
85
90
78
75
92
85
90
78
75
92
15
Array Initialization
Array elements can be initialized within declaration
statements
Initializing elements must be included in braces
Example:
const int NUMGALS = 20;
int gallons[NUMGALS] =
{19, 16, 14, 19, 20, 18, // initializing values
12, 10, 22, 15, 18, 17, // can extend across
16, 14, 23, 19, 15, 18, // multiple lines
21, 5};
16
17
18
19
Arrays as Arguments
Array elements are passed to a called function in
same manner as individual scalar variables
Example:
findMax(grades[2], grades[6]);
20
21
22
23
24
25
Two-Dimensional Arrays
16
15
25
9
27
2
52
6
10
26
27
28
29
160
150
250
90
270
20
520
60
100
30
31
32
33
34
35
36
37
Summary
One-dimensional array: a data structure that stores
a list of values of same data type
Must specify data type and array size
Example:
int num[100]; creates an array of 100 integers
38
Summary (cont'd.)
Two-dimensional array is declared by listing both a
row and column size with data type and name of
array
Arrays may be initialized when they are declared
For two-dimensional arrays, you list the initial values,
in a row-by-row manner, within braces and separating
them with commas
39
40
Search Algorithms
Linear (sequential) search
Each item in the list is examined in the order in which it
occurs until the desired item is found or the end of the
list is reached
List doesnt have to be in sorted order to perform the
search
Binary search
Starting with an ordered list, the desired item is first
compared with the element in the middle of the list
If item is not found, you continue the search on either
the first or second half of the list
A First Book of C++ 4th Edition
41