Chapter 6 Arrays: Lecturer: Mrs Rohani Hassan
Chapter 6 Arrays: Lecturer: Mrs Rohani Hassan
Chapter 6 Arrays: Lecturer: Mrs Rohani Hassan
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
1
Objectives
To describe why an array is necessary in programming (§6.1).
To learn how to declare an array (§6.2.1).
To access array elements using indexed variables (§6.2.2).
To initialize the values in an array (§6.2.3).
To develop and invoke functions with array arguments (§§6.3-6.4).
To declare and create two-dimensional arrays (§6.7).
(Optional) To declare and create multidimensional arrays (§6.8).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
2
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double myList [10];
myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34.0
myList[7] 45.45
myList[8] 99.993
myList[9] 111.23
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
3
Declaring Array Variables
datatype arrayRefVar[arraySize];
Example:
double myList[10];
C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
double myList[size]; // Correct
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
4
Arbitrary Initial Values
When an array is created, its elements are assigned
with arbitrary values.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5
Indexed Variables
The array elements are accessed through the index. Array
indices are 0-based; that is, they start from 0 to arraySize-1.
In the example in Figure 6.1, myList holds ten double
values and the indices are from 0 to 9.
arrayName[index];
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
7
No Bound Checking
C++ does not check array’s boundary. So,
accessing array elements using subscripts beyond
the boundary (e.g., myList[-1] and myList[11])
does not does cause syntax errors, but the operating
system might report a memory access violation.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
8
Array Initializers
Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1,
..., valuek};
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
9
Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:
double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
10
CAUTION
Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
Splitting it would cause a syntax error. For
example, the following is wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
11
Implicit Size
C++ allows you to omit the array size when
declaring and creating an array using an initilizer.
For example, the following declaration is fine:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
12
Partial Initialization
C++ allows you to initialize a part of the array. For
example, the following statement assigns values
1.9, 2.9 to the first two elements of the array. The
other two elements will be set to zero. Note that if
an array is declared, but not initialized, all its
elements will contain “garbage”, like all other local
variables.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
13
Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
14
Initializing arrays with random
values
The following loop initializes the array myList with random
values between 0 and 99:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
15
Printing arrays
To print an array, you have to print each element in the array
using a loop like the following:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
16
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays
Dallas:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
17
Copying Arrays
Can you copy array using a syntax like this?
list = myList;
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
19
Finding the Largest Element
Use a variable named max to store the largest element.
Initially max is myList[0]. To find the largest element in
the array myList, compare each element in myList with
max, update max if the element is greater than max.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
20
Finding the smallest index of the
largest element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
21
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
int main()
{ After the array is created
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 0
{ 2 0
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
22
animation
Trace Program with Arrays
i becomes 1
int main()
{ After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 0
0
values[i] = values[i] + values[i-1]; 2
3 0
} 4 0
values[0] = values[1] + values[4];
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
23
animation
Trace Program with Arrays
i (=1) is less than 5
int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 0
} 3 0
4 0
values[0] = values[1] + values[4];
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
24
animation
Trace Program with Arrays
After this line is executed, value[1] is 1
int main()
{ After the first iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 0
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
25
animation
int main()
{
int values[5]; After the first iteration
{ 1
2
1
values[i] = values[i] + 3 0
values[i-1]; 4 0
}
values[0] = values[1] +
values[4];
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
26
animation
Trace Program with Arrays
i (= 2) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the first iteration
{ 0 0
values[i] = values[i] + 1 1
values[i-1]; 2 0
3 0
} 4 0
values[0] = values[1] +
values[4];
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
27
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
int main()
{ After the second iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
28
animation
Trace Program with Arrays
After this, i becomes 3.
int main()
{ After the second iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
29
animation
Trace Program with Arrays
i (=3) is still less than 5.
int main()
{ After the second iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
30
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
int main()
{ After the third iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
31
animation
Trace Program with Arrays
After this, i becomes 4
int main()
{ After the third iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
32
animation
Trace Program with Arrays
i (=4) is still less than 5
int main()
{ After the third iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
33
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
int main()
{ After the fourth iteration
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
} 4 10
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
34
animation
Trace Program with Arrays
After i++, i becomes 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{ After the fourth iteration
values[i] = values[i] + values[i-1];
} 0 0
values[0] = values[1] + values[4]; 1 1
} 2 3
3 6
4 10
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
35
animation
int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the fourth iteration
{
values[i] = values[i] + values[i-1]; 0
1
0
1
} 2 3
} 4 10
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
36
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
int main()
{
int values[5];
for (int i = 1; i < 5; i++) 0 11
{ 1 1
} 3 6
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
37
Example: Testing Arrays
Objective: The program receives 6 numbers from
the user, finds the largest number and counts the
occurrence of the largest number entered.
Suppose you entered 3, 5, 2, 5, 5, and 5, the
largest number is 5 and its occurrence count is 4.
TestArray Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
38
Example: Assigning Grades
Objective: read student scores (int), get the best
score, and then assign grades based on the
following scheme:
– Grade is A if score is >= best–10;
– Grade is B if score is >= best–20;
AssignGrade
– Grade is C if score is >= best–30;
– Grade is D if score is >= best–40; Run
– Grade is F otherwise.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
39
Passing Arrays to Functions
Just as you can pass single values to a function,
you can also pass an entire array to a function.
Listing 6.3 gives an example to demonstrate how
to declare and invoke this type of functions.
PassArrayDemo
Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
40
Passing Size along with Array
Normally when you pass an array to a function, you
should also pass its size in another argument. So the
function knows how many elements are in the array.
Otherwise, you will have to hard code this into the
function or declare it in a global variable. Neither is
flexible or robust.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
41
Pass-by-Reference
Passing an array variable means that the starting
address of the array is passed to the formal
parameter. The parameter inside the function
references to the same array that is passed to the
function. No new arrays are created. This is pass-
by-reference.
PassByReferenceDemo
Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
42
const Parameters
Passing arrays by reference makes sense for performance
reasons. If an array is passed by value, all its elements must
be copied into a new array. For large arrays, it could take
some time and additional memory space. However, passing
arrays by reference could lead to errors if your function
changes the array accidentally. To prevent it from
happening, you can put the const keyword before the array
parameter to tell the compiler that the array cannot be
changed. The compiler will report errors if the code in the
function attempts to modify the array.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
44
Modifying Arrays in Functions, cont.
However, you can circumvent this restriction by passing
two array arguments in the function, as follows:
// newList is the reversal of list
void reverse(const int list[], list newList[], int size)
list
newList
ReverseArray Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
45
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
46
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
47
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 0
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
48
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
49
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
50
animation
list 1 2 3 4 5 6
newList 0 0 0 0 0 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
51
animation
newList 0 0 0 0 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
52
animation
list 1 2 3 4 5 6
newList 0 0 0 0 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
53
animation
list 1 2 3 4 5 6
newList 0 0 0 0 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
54
animation
list 1 2 3 4 5 6
newList 0 0 0 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
55
animation
list 1 2 3 4 5 6
newList 0 0 0 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
56
animation
list 1 2 3 4 5 6
newList 0 0 0 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
57
animation
list 1 2 3 4 5 6
newList 0 0 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
58
animation
list 1 2 3 4 5 6
newList 0 0 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
59
animation
list 1 2 3 4 5 6
newList 0 0 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
60
animation
list 1 2 3 4 5 6
newList 0 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
61
animation
list 1 2 3 4 5 6
newList 0 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
62
animation
list 1 2 3 4 5 6
newList 0 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
63
animation
list 1 2 3 4 5 6
newList 6 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
64
animation
list 1 2 3 4 5 6
newList 6 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
65
animation
list 1 2 3 4 5 6
newList 6 5 4 3 2 1
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
66
Two-dimensional Arrays
// Declare array ref var
dataType arrayName[rowSize][columnSize];
int matrix[5][5];
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
67
Two-dimensional Array Illustration
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3]
[1] [1] 4 5 6
[1]
[2] [2] 7 [2] 7 8 9
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
68
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
69
Initializing Arrays with Random Values
The following loop initializes the array with random
values between 0 and 99:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
74
Passing Two-Dimensional Arrays
to Functions
You can pass a two-dimensional array to a
function; however, C++ requires that the
column size to be specified in the function
declaration. Listing 6.11 gives an example with
a function that returns the sum of all the
elements in a matrix.
PassTwoDimensionalArray Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
75
Example: Grading Multiple-
Choice Test
Objective: write a
Students’ Answers to the Questions:
0 1 2 3 4 5 6 7 8 9
program that grades
Student 0 A B A C C D E E A D multiple-choice test.
Student 1 D B A B C A E E A D
Student 2 E D D A C B E E A D
Student 3 C B A E D C E E A D Key to the Questions:
Student 4 A B D C C D E E A D 0 1 2 3 4 5 6 7 8 9
Student 5 B B E C C D E E A D
Student 6 B B A C C D E E A D Key D B D C C D A E A D
Student 7 E B E C C D E E A D
GradeExam Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
76
Example: Computing Taxes
Using Arrays
Listing 5.9, ComputeTaxWithFunction.cpp, simplified
Listing 3.5, ComputeTaxWithSelectionStatement.cpp.
Listing 5.9 can be further improved using arrays. For
each filing status, there are six tax rates. Each rate is
applied to a certain amount of taxable income.
ComputeTax Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
77
Refine the table
Rotate
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
79
Declare Two Arrays
6000 27950 67700 141250 307050 Single filer
12000 46700 112850 171950 307050 Married jointly
6000 23350 56425 85975 153525 Married separately
10000 37450 96745 156600 307050 Head of household
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
80
Multidimensional Arrays
In the preceding section, you used a two-dimensional array
to represent a matrix or a table. Occasionally, you will
need to represent n-dimensional data structures. In C++,
you can create n-dimensional arrays for any integer n.
double scores[10][5][2];
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
81
Example: Calculating Total Scores
TotalScore Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
82
Example: Guessing Birth Date
Listing 3.2, GuessBirthDate.cpp, gives a
program that guesses a birth date. The
program can be simplified by storing the
numbers in five sets in a three dimensional
array and prompts the user for the answers
using a loop, as shown in Listing 6.15:
GuessBirthDateUsingArray Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
83