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 MultipleSubscripted 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
4.3 Declaring Arrays
• Declaring arrays - specify:
– Name
– Type of array
– Number of elements
– Examples
int c[ 10 ];
float hi[ 3284 ];
• Declaring multiple arrays of same type
– Similar format as other variables
– Example
int b[ 100 ], x[ 27 ];
4.4 Examples Using Arrays
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
– If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
– Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore n is a 5 element array
#include <iostream.h>
Outline
#include <iomanip.h> Notice how the array is 1. Initialize array using
declared and elements a declaration
int main() referenced.
{
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
2. Define loop
3. Print out each array
cout << "Element" << setw( 13 ) << "Value" << endl;
return 0;
Element Value
0 32
Program Output
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
2000 Prentice Hall, Inc. All rights reserved.
1// Fig. 4.7: fig04_07.cpp 8
2// A const object must be initialized Outline
3
4int main() 1. Initialize const
5{ variable
6 const int x; // Error: x must be initialized
7
Notice that const variables must be 2. Attempt to modify
8 x = 7; // Error: cannot modify because
initialized a constthey
variable
cannot be modified variable
9 later.
10 return 0;
11 }
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 ***
4.4 Examples Using Arrays
• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples:
char string1[] = "hello";
char string1[] = { 'h', 'e', 'l', 'l', 'o',
'\0’ };
– Subscripting is the same as for a normal array
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
• Input from keyboard
char string2[ 10 ];
cin >> string2;
– Takes user input
– Side effect: if too much text entered, data written beyond array
2000 Prentice Hall, Inc. All rights reserved.
// Fig. 4_12: fig04_12.cpp
10
// Treating character arrays as strings
#include <iostream.h>
Outline
int main() {
1. Initialize strings
char string1[ 20 ], string2[] = "string literal";
Inputted strings are
separated by
cout << "Enter a string: ";
}
Notice how string
3. Print string
Enter a string: Hello there elements are referenced
string1 is: Hello like arrays.
string2 is: string literal
string1 with spaces between characters is:
H e l l o
string1 is: there
Program Output
4.5 Passing Arrays to Functions
• Specify the name without any brackets
– To pass array myArray declared as
int myArray[ 24 ];
to function myFunction, a function call would resemble
myFunction( myArray, 24 );
– Array size is usually passed to function
• Arrays passed call-by-reference
– Value of name of array is address of the first element
– Function knows where the array is stored
• Modifies original memory locations
• Individual array elements passed by call-by-value
– pass subscripted name (i.e., myArray[ 3 ]) to function
4.5 Passing Arrays to Functions
• Function prototype:
void modifyArray( int b[], int arraySize );
– Parameter names optional in prototype
• int b[] could be simply int []
• int arraysize could be simply int
14
18 int i, a[ arraySize ] = { 0, 1, 2, 3, 4 };
19
22
25 0 1 2 3 4
26 cout << endl; The values of the modified array are:
27
0 2 4 6 8
28 // array a passed call-by-reference
29 modifyArray( a, arraySize );
30
31 cout
2000<<Prentice Hall, Inc.
"The values Allmodified
of the rights reserved.
array are:\n";
32
14
33 for ( i = 0; i < arraySize; i++ )
Outline
34 cout << setw( 3 ) << a[ i ];
35
39
3. Print changes.
40 modifyElement( a[ 3 ] );
41
42 cout << "The value of a[3] is " << a[ 3 ] << endl; 3.1 Function Definitions
43
Parameter names required in function
44 return 0;
definition
45 }
46
50 {
Effects of passing array element call-by-value:
51 for ( int j = 0; j < sizeOfArray; j++ )
52 b[ j ] *= 2;
58 {
4.6 Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element
4.6 Sorting Arrays
• Example:
– Original: 3 4 2 6 7
– Pass 1: 3 2 4 6 7
– Pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
4.9 MultipleSubscripted Arrays
• Multiple subscripts - tables with rows, columns
– Like matrices: specify row, then column.
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
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
4.9 MultipleSubscripted Arrays
• Referenced like normal
cout << b[ 0 ][ 1 ];
– Will output the value of 0
– Cannot reference with commas
cout << b( 0, 1 );
• Will try to call function b, causing a syntax error
#include <iostream.h>
Outline
#include <iomanip.h>
36
<< maximum( studentGrades, students, exams ) << '\n';
Outline
37 for ( int person = 0; person < students; person++ )
38 cout << "The average grade for student " << person << " is " 2. Call functions
39 << setiosflags( ios::fixed | ios::showpoint ) minimum, maximum,
40 << setprecision( 2 )
and average
41 << average( studentGrades[ person ], exams ) << endl;
42
43 return 0; 3. Define functions
44 }
45
48 {
50
52
54
56 lowGrade = grades[ i ][ j ];
57
58 return lowGrade;
59 }
60
63 {
64 int highGrade = 0;
69
for ( int j = 0; j < tests; j++ )
Outline
70 if ( grades[ i ][ j ] > highGrade )
73 return highGrade;
74 }
75
78 {
79 int total = 0;
80
82 total += setOfGrades[ i ];
83
85 }
86
89 {
91
94
97 << grades[ i ][ j ];
98 }
int frequency[ 10 ] = { 0 },
response[ responseSize ] =
{ 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 };
total += answer[ j ];
<< total << " / " << arraySize << " = "
<< setprecision( 4 )
3.1 Define function
71 bubbleSort( answer, size );
72 cout << "\n\nThe sorted array is";
median
73 printArray( answer, size );
74 cout << "\n\nThe median is element " << size / 2
3.1.1 Sort Array
75 << " of\nthe sorted " << size 3.1.2 Print middle
76 << " element array.\nFor this run the median is " element
77 << answer[ size / 2 ] << "\n\n";
78 }
79
3.2 Define function
80 void mode( int freq[], int answer[], int size )
mode
81 {
82 int rating, largest = 0, modeValue = 0;
3.2.1 Increase
83
frequency[]
84 cout << "\n********\n Mode\n********\n";
depending on
response[]
85
86 for ( rating = 1; rating <= 9; rating++ )
87 freq[ rating ] = 0;
88 Notice how the subscript in
89 for ( int j = 0; j < size; j++ ) frequency[] is the value of an
90 ++freq[ answer[ j ] ]; element in response[]
91 (answer[]).
92 cout << "Response"<< setw( 11 ) << "Frequency"
93 << setw( 19 ) << "Histogram\n\n" << setw( 55 )
94 << "1 1 2 2\n" << setw( 56 )
95 2000 Prentice
<< "5 Hall,
0 Inc. 5All rights
0 reserved.
5\n\n";
96 29
97 for ( rating = 1; rating <= 9; rating++ ) { Outline
98 cout << setw( 8 ) << rating << setw( 11 )
99 << freq[ rating ] << " "; 3.3 Define bubbleSort
100
101 if ( freq[ rating ] > largest ) {
102 largest = freq[ rating ];
103 modeValue = rating;
104 }
105
106 for ( int h = 1; h <= freq[ rating ]; h++ )
107 cout << '*';
Print stars depending on value of
108 frequency[]
109 cout << '\n';
110 }
111
112 cout << "The mode is the most frequent value.\n"
113 << "For this run the mode is " << modeValue
114 << " which occurred " << largest << " times." << endl;
115 }
116
117 void bubbleSort( int a[], int size )
118 {
119 int hold;
120 2000 Prentice Hall, Inc. All rights reserved.
121 for ( int pass = 1; pass < size; pass++ ) 30
122 Outline
123 for ( int j = 0; j < size - 1; j++ )
3.3 Define bubbleSort
124
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.
******** 31
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
1 1 2 2
Program Output
5 0 5 0 5
1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.