Chapter 4 - Arrays: 2000 Prentice Hall, Inc. All Rights Reserved
Chapter 4 - Arrays: 2000 Prentice Hall, Inc. All Rights Reserved
Chapter 4 - Arrays
Outline
4.1 Introduction
4.2 Arrays
4.3 Declaring Arrays
4.4 Examples Using Arrays
4.5 Passing Arrays to Functions
4.6 Sorting Arrays
4.7 Case Study: Computing Mean, Median and Mode Using Arrays
4.8 Searching Arrays: Linear Search and Binary Search
4.9 Multiple-Subscripted Arrays
4.10 Thinking About Objects: Identifying a Class's Behaviors
4.1 Introduction
• Arrays
– Structures of related data items
– Static entity - same size throughout program
• A few types
– C-like, pointer-based arrays
– C++, arrays as objects
4.2 Arrays
• Array
– Consecutive group of memory locations
– Same name and type
• To refer to an element, specify
– Array name and position number
• Format: arrayname[ position number ]
– First element at position 0
– n element array c:
c[ 0 ], c[ 1 ]…c[ n - 1 ]
• Array elements are like normal variables
c[ 0 ] = 3;
cout << c[ 0 ];
• Performing operations in subscript. If x = 3,
c[ 5 – 2 ] == c[ 3 ] == c[ x ]
2000 Prentice Hall, Inc. All rights reserved.
4
4.2 Arrays
Name of array (Note
that all elements of
this array have the
same name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
Fig04_07.cpp:
Error E2304 Fig04_07.cpp 6: Constant variable 'x' must be
initialized in function main() Program Output
Error E2024 Fig04_07.cpp 8: Cannot modify a const object in
function main()
*** 2 errors in Compile ***
125 if ( a[ j ] > a[ j + 1 ] ) {
3.3 Define printArray
126 hold = a[ j ];
Bubble sort: if elements out of order,
127 a[ j ] = a[ j + 1 ];
swap them.
128 a[ j + 1 ] = hold;
129 }
130 }
131
133 {
135
136 if ( j % 20 == 0 )
138
140 }
141
} 2000 Prentice Hall, Inc. All rights reserved.
******** 24
Mean
********
Outline
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
4. Program Output
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788
********
Median
********
The unsorted array of responses is
6 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
The sorted array is
1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
The median is element 49 of
the sorted 99 element array.
For this run the median is 7
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
• Initialize
1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4