Chap10 - Array
Chap10 - Array
2
Array - Example
score
95 …. …. …. 70 …. …. ….
0 1 2 3 4 5 6 7
subscript / index
3
Array - Example
▪ Example: To store the values 95 and 70
into first and fifth locations respectively:
score
95 …. …. …. 70 …. …. ….
0 1 2 3 4 5 6 7
4
Array - Introduction
5
8 identifiers without Array Using Array
int score1;
int score2;
int score3;
int score4; int score[7];
int score5;
int score6;
int score7; score[0] = 23;
score[1] = 56;
score1 = 23; score[2] = 76;
score2 = 56; score[3] = 86;
score3 = 76; score[4] = 88;
score4 = 86; score[5] = 93;
score5 = 88; score[6] = 45;
score6 = 93;
score7 = 45; 6
Array – One dimensional
▪ Example: ARR_1D is a 1-D array with 5
elements
ARR_1D
2 4 9 5 8
0 1 2 3 4
9
Array components-Assignment
• Cannot assign one array to another array
Example:
int x[5] = {1,2,3,4,5}, y[5];
y = x; Invalid
• However:
for (int i=0; i<5; i++)
y[i] = x[i]; Valid
10
Array – Initialization
▪ Array initialization:
Initialization with definition:
compile-time initializing
11
Array Initialization - Example
▪ E.g. (i) int score[8] = { 95, 80, 85, 67, 70, 60, 88, 90 };
score
95 80 85 67 70 60 88 90
0 1 2 3 4 5 6 7
costs
1.20 5.50 2.50 7.25
0 1 2 3
12
Array Declaration & Initialization
▪ The squares brackets [ ] can be left empty
if all elements are present in the brackets.
Empty
int ARR[3] = { 2 };
int ARR[3] = { 2,0,0 }; same
int ARR[ ] = { 2,0,0 };
14
8 identifiers Array Array
without Array (Basic Initialization) (compile-time initializing)
int score1;
int score2;
int score3; int score[7];
int score4;
int score5;
int score6; score[0] = 23; int score[7] =
int score7; score[1] = 56; {23,56,76,86,88,93,45};
score[2] = 76;
score1 = 23; score[3] = 86;
score2 = 56; score[4] = 88;
score3 = 76; score[5] = 93;
score4 = 86; score[6] = 45;
score5 = 88;
score6 = 93;
score7 = 45; 15
Array – Index out of bound
▪ C++ does not check for the boundary of an
array. The programmer must check that all
indexes referenced are valid (i.e. within the
range of the array).
� common mistake:
int ARR[10];
Boundary/range of an array.
Begin from 0 - 9
ARR[10]= 45; /* Error: index out of bound! */
16
Operation on Array
testscores
67 50 95
0 1 2 3 4 5 6 7
18
Operation on Array
▪ Using values keyed in from keyboard:
for (i=0; i<8; i++){
or
cin >> score;
for (i=0; i<8; i++)
testscores [i] = score; cin >> testscore[i];
}
20
Operation on Array - Example
⦿ Reading data into the array sales
for(index = 0; index < 10; index++)
cin >> sales[index];
21
Operation on Array - Example
⦿ Find the sum and average from the array sales
int sum = 0;
for(index = 0; index < 10; index++)
sum += sales[index];
average = sum / 10.0;
Output: ARR[0] = 5
ARR[1] = 7
ARR[2] = 9
ARR[3] = 11
24
Manipulation of Array elements
▪ From one array, ARR, produce another array,
SQUARE:
int ARR[8] = { 2, 1, 9, 6, 5, 4, 7, 3 };
int SQUARE[8];
:
for ( i= 0; i< 8; i++)
SQUARE[i] = ARR[i] * ARR[i];
SQUARE
4 1 81 36 25 16 49 9
25
Manipulation of Indexes
⦿ The index can be written in many ways.
⦿ Example:
int x[5]={1, 2, 3, 8, 7};
int i = 2;
num1 1 2 3 4 5
[0] [1] [2] [3] [4]
num2 5 4 3 2 1
[0] [1] [2] [3] [4]
27
Array - Exercise
e.g ARR_2D[1][3]=7;
▪ The element is accessed by using:
array_name[row number][column number]
29
Array – Two dimensional
▪ Contents are listed row by row, or each row
contents are enclosed separately in braces.
0 2 4 6 8
ARR_2D 1 1 3 5 7
2 1 4 9 16
0 1 2 3
One-Dimensional Two-Dimensional
Declaration int Arr[5]; int Arr[2][3];
Referencing int Arr[5] ={1, 2, 3, int Arr[2][3]
/ 4, 5} ; = {{2, 2, 2}, {3, 3, 3}};
Initialization
31
Two dimensional array – Processing
Algorithm
0 2 4 6 8
ARR_2D 1 1 3 5 7
2 1 4 9 16
0 1 2 3
Single Row processing:
E.g. Sum up total of 2nd row of ARR_2D array
row = 1;
for ( col = 0; col < 4; col++ )
sum += ARR_2D [ row ][ col ];
32
Two dimensional array – Processing
Algorithm
0 2 4 6 8
ARR_2D 1 1 3 5 7
2 1 4 9 16
0 1 2 3
Single Column processing:
E.g. Sum up total of 4th column of ARR_2D array
col = 3;
for ( row = 0; row < 3; row++ )
sum += ARR_2D [ row ][ col ];
33
Two dimensional array – Processing
Algorithm
0 2 4 6 8
ARR_2D 1 1 3 5 7
2 1 4 9 16
0 1 2 3
Row by Column processing:
E.g. Find the grand total of ARR_2D
for ( row = 0; row < 3; row++ )
for ( col = 0; col < 4; col++ )
GrandTotal += ARR_2D [ row ][ col ];
34
Two dimensional array – Processing
Algorithm
0 2 4 6 8
ARR_2D 1 1 3 5 7
2 1 4 9 16
0 1 2 3
Colum by Row processing:
E.g. Find the grand total of ARR_2D
for ( col = 0; col < 4; col++ )
for ( row = 0; row < 3; row++ )
GrandTotal += ARR_2D [ row ][ col ];
35
Passing Array to Function
(Individual element)
⦿ Using pass-by-value – similar to passing
values from actual parameters to formal
parameters.
⦿ Example:
void initialize (int x)
{
....;
}
⦿ Function call:
initialize (list[5]);
36
Passing Array to Function
(Individual element) - Example
#include <iostream>
#define SIZE 15
using namespace std;
int findLargest(int, int);
int main(){
int list[SIZE] = { 5, 2, 7, 8, 36, 4, 2, 68, 22, 34,
11 };
Pass an individual int largest, i;
element of the array
for (largest = list[0], i = 1; i<SIZE; i++)
largest = findLargest(list[i], largest);
Normal variable cout << "The largest number is " << largest
declared as formal << endl;
return 0;
parameter to }
receive value from
the array element int findLargest(int x, int largest){
if (x > largest)
return x;
else
return largest; 37
Passing Array to Function
(Whole array)
⦿ Using pass-by-reference – Do not use the symbol &
when declaring an array as a formal parameter.
int main() {
pass only the int list[SIZE] = { 5, 2, 7, 8, 36, 4, 2, 68,
22, 34, 11 };
name of the array int largest;
largest = findLargest(list);
cout << "The largest number is " <<
largest ;
formal parameter of the return 0;
function definition must }
be an array type
int findLargest (int x[]) {
int largest, i;
size of the array does for (largest = x[0], i = 1; i < SIZE; i++)
not need to be specified if (x[i] > largest)
largest = x[i];
return largest; 39
Passing Array to Function
(Whole array) - Example
#include <iostream> void multiply2(int x[], int size)
#define SIZE 5 { int i;
using namespace std;
cout << "Printed from multiply2\
void multiply2(int x[], int size);
n";
int main()
{ for (i = 0; i < size; i++)
int i, base[SIZE] = { 3, 7, 1, 5, 8 }; { x[i] *= 2;
cout << "Before function call : \n"; cout << x[i] << " ";
for (i = 0; i < 5; i++) }
cout << base[i] << " "; cout << endl << endl;
cout << endl << endl;
}
multiply2(base, SIZE);
int * getRandom( )
42
Function returns an Array - Example
}
43
Introduction to Search Algorithms
44
Linear Search Example
17 23 5 11 2 29 3
45
Linear Search Tradeoffs
• Benefits
− Easy algorithm to understand
− Array can be in any order
• Disadvantage
− Inefficient (slow): for array of N elements,
examines N/2 elements on average for value
that is found in the array, N elements for value
that is not in the array
46
Binary Search Algorithm
1. Divide a sorted array into three sections:
− middle element
− elements on one side of the middle element
− elements on the other side of the middle element
2. If the middle element is the correct value, done.
Otherwise, go to step 1, using only the half of
the array that may contain the correct value.
3. Continue steps 1 and 2 until either the value is
found or there are no more elements to
examine.
47
Binary Search Example
48
Binary Search Tradeoffs
• Advantage
− Much more efficient than linear search
Disadvantage
− Requires that array elements be sorted
49
Introduction to Sorting Algorithms
50
Bubble Sort Algorithm
51
Bubble Sort Example
17 23 5 11
52
Bubble Sort Example (continued)
After first pass, array numlist3 contains
In order from
previous pass
17 5 11 23
53
Bubble Sort Example (See pr9-04.cpp)
After second pass, array numlist3 contains
In order from
previous passes
5 11 17 23
54
Bubble Sort Tradeoffs
• Benefit
− Easy to understand and implement
• Disadvantage
− Inefficiency makes it slow for large arrays
55
Selection Sort Algorithm
56
Selection Sort Example
11 2 29 3
Smallest element is 2. Exchange 2 with
element in 1st array position (i.e. element 0).
Now in order
2 11 29 3
57
Selection Sort – Example (See pr9-05.cpp)
Now in order
2 3 11 29
58
Selection Sort Tradeoffs
• Benefit
− More efficient than Bubble Sort, due to fewer
exchanges
• Disadvantage
− Considered harder to understand as compared
to Bubble Sort
59