mech215-lec10

1
Arrays
Outline
Introduction
Arrays
Declaring Arrays
Examples Using Arrays
 2003 Prentice Hall, Inc. All rights reserved.
2
Introduction
• Arrays
– Structures (collection) of related data items (same
type data items)
– Static entity (maintain the same size throughout
program execution)
 2003 Prentice Hall, Inc. All rights reserved.
3
Arrays
• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
–
–
–
–
Specify array name and position number (index)
Format: arrayname[ position_number ]
An Array index must be an integer
First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1
 2003 Prentice Hall, Inc. All rights reserved.
4
Arrays
• Array elements like other variables
– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
• Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]
int a = 6, b= 5;
c[ a + b ] += 2;
 2003 Prentice Hall, Inc. All rights reserved.
5
Arrays
Name
that
this
same
of array (Note
all elements of
array have the
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
Position number of the
element within array c
 2003 Prentice Hall, Inc. All rights reserved.
Value
6
Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
– arraySize: MUST be a positive integer
• Declaring multiple arrays of same type
– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
 2003 Prentice Hall, Inc. All rights reserved.
7
Declaring Arrays
• Array of type char can be used to store a
character string
– string objects have so far been used to store
character strings
– Arrays can do the same thing (more later)
 2003 Prentice Hall, Inc. All rights reserved.
8
Examples Using Arrays
• Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers  rightmost elements 0
• If too many  syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted  initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
9
// Fig. 7.3: fig07_03.cpp
// Initializing an array.
#include <iostream>
Outline
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int main()
{
int n[ 10 ];
Declare a 10-element array of
integers.
to 0 using a
for loop. Note that the array
nhas
to elements
0
n[0] to n[9].
array
// n is an array of Initialize
10 integers
// initialize elements of array
for ( int i = 0; i < 10; i++ )
n[ i ] = 0;
// set element at location i to 0
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
return 0;
// indicates successful termination
10
Outline
} // end main
Element
0
1
2
3
4
5
6
7
8
9
Value
0
0
0
0
0
0
0
0
0
0
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 7.4: fig07_04.cpp
// Initializing an array with a declaration.
#include <iostream>
11
Outline
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
Note the use of the initializer
int main()
list.
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
return 0;
// indicates successful termination
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
Element
0
1
2
3
4
5
6
7
8
9
Value
32
27
64
18
95
14
90
70
60
37
12
Outline
 2003 Prentice Hall, Inc.
All rights reserved.
13
Examples Using Arrays
• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 7.5: fig07_05.cpp
// Initialize array s to the even integers from 2 to 20.
#include <iostream>
14
Outline
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
Note use of const keyword.
can
int main()
Only const variables
{
specify array sizes.
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ];
// array s
for ( int i = 0; i < arraySize;
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 )
The program becomes more
scalable when we set the array
has 10 elements
size using a const variable.
i++ ) // We
setcan
thechange
valuesarraySize,
and all the loops will still
work (otherwise, we’d have to
<< "Value"update
<< endl;
every loop in the
program).
 2003 Prentice Hall, Inc.
All rights reserved.
24
25
26
27
28
29
30
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
return 0;
15
Outline
// indicates successful termination
} // end main
Element
0
1
2
3
4
5
6
7
8
9
Value
2
4
6
8
10
12
14
16
18
20
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Fig. 7.6: fig07_06.cpp
// Using a properly initialized constant variable.
#include <iostream>
16
Outline
using std::cout;
using std::endl;
int main()
{
const int x = 7;
Proper initialization of
const variable. (cannot be
modified later)
// initialized constant variable
cout << "The value of constant variable x is: "
<< x << endl;
return 0;
// indicates successful termination
} // end main
The value of constant variable x is: 7
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 7.7: fig07_07.cpp
// A const object must be initialized.
int main()
{
const int x;
// Error: x
17
Outline
Uninitialized const results
in a syntax error. Attempting
to modify the const is
must
be initialized
another
error.
x = 7;
// Error: cannot modify a const variable
return 0;
// indicates successful termination
} // end main
d:\cpphtp7_examples\ch04\Fig07_07.cpp(8) : error C2166:
l-value specifies const object
 2003 Prentice Hall, Inc.
All rights reserved.
Summing the elements of an array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
18
Outline
// Fig. 7.8: fig07_08.cpp
// Compute the sum of the elements of the array.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cout << "Total of array element values is " << total << endl;
return 0;
// indicates successful termination
} // end main
Total of array element values is 55
 2003 Prentice Hall, Inc.
All rights reserved.
19
Showing array data graphically
– Example: show distribution of grades of a specific
class
– Grade distribution is stored in an array of 11
elements, each corresponds to a category of grade
• Example:
– category 1: [0..9]
– category 2: [10..19]
– etc…
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 7.9: fig07_09.cpp
// Histogram printing program.
#include <iostream>
20
Outline
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int main()
{
const int arraySize = 11;
int n[ arraySize ] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };
cout << “Grade Distribution:" << endl;
// for each
for ( int i
// output
if (i ==
cout
else if
cout
else
cout
element of array n, output a bar in histogram
= 0; i < arraySize; i++ ) {
bar labels (“0-9:”,…“90-99:”, “100:”)
0)
<< “0-9:”;
(i == 10)
<< “100:”;
<< i * 10 << “-” << (i * 10) + 9<< “: ”;
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
// print bar of asterisks
for ( int stars = 0; stars < n[ i ]; stars++ )
cout << '*';
cout << endl;
// start next line of output
21
Outline
Number of students with grades
in the range: 10*i--10*i+9.
} // end outer for structure
return 0; // indicates successful termination
} // end main
Grade
0-9:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69:
70-79:
80-89:
90-99:
100:
distribution
*
* *
* * * *
* *
*
 2003 Prentice Hall, Inc.
All rights reserved.
22
Outline
Using Elements of array as counters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 7.10: fig07_10.cpp
// Roll a six-sided die 6000000 times.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
Remake of old program to
roll dice. An array is used
instead of 6 regular variables,
and the proper element can be
updated easily (without
needing a switch).
using std::setw;
#include <cstdlib>
#include <ctime>
int main()
{
const int arraySize = 7; // ignore element zero
This
int frequency[ arraySize ] = { 0 };
srand( time( 0 ) );
// seed random-number
creates a number
between 1 and 6, which
determines the index of
generator
frequency[] that should
be incremented.
// roll die 6000000 times
for ( int roll = 1; roll <= 6000000; roll++ )
frequency[ 1 + rand() % 6 ]++;
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
23
cout << "Face" << setw( 13 ) << "Frequency" << endl;
Outline
// output frequency elements 1-6 in tabular format
for ( int face = 1; face < arraySize; face++ )
cout << setw( 4 ) << face
<< setw( 13 ) << frequency[ face ] << endl;
return 0;
// indicates successful termination
} // end main
Face
1
2
3
4
5
6
Frequency
1000167
1000149
1000152
998748
999626
1001158
 2003 Prentice Hall, Inc.
All rights reserved.
24
Using arrays to summarize survey results
Forty students were asked to rate the quality of
the food in the student cafeteria on a scale of
1 to 10 (1 meaning awful and 10 meaning
excellent). Place the 40 responses in an integer
array and summarize the results of the poll
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
25
// Fig. 7.11: fig07_11.cpp
// Student poll program.
#include <iostream>
Outline
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
Array declared as const int 
this means its value cannot
and should not change
int main()
{
// define array sizes
const int responseSize = 40;
const int frequencySize = 11;
// size of array responses
// size of array frequency
// place survey responses in array responses
const int responses[ responseSize ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8,
10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7,
5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
// initialize frequency counters to 0
int frequency[ frequencySize ] = { 0 };
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// for each answer, select value of an element of array
// responses and use that value as subscript in array
// frequency to determine element to increment
for ( int answer = 0; answer < responseSize; answer++ )
frequency[ responses[answer] ]++;
26
Outline
responses[answer] is
This
determines the index in
frequency[] to increment.
format
// display results
the rating (from
1 to 10).
cout << "Rating" << setw( 17 ) << "Frequency"
<< endl;
// output frequencies in tabular
for ( int rating = 1; rating < frequencySize; rating++ )
cout << setw( 6 ) << rating
<< setw( 17 ) << frequency[ rating ] << endl;
return 0;
// indicates successful termination
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
Rating
1
2
3
4
5
6
7
8
9
10
27
Frequency
2
2
2
2
5
11
5
7
1
3
Outline
NOTE: what happens when the data in responses
contain an invalid value (e.g., 13)… C++ does not
do a boundary check  logic error happens
(NOT SYNTAX ERROR)
 2003 Prentice Hall, Inc.
All rights reserved.
Using character arrays to store and
manipulate strings
• string has been used to store character strings
– A string such as “Hello” is an array of characters
• A character array can be declared and
initialized as:
– char string1[] = “first”;
– The size of array string1 is not explicitly defined, but it
is determined by the compiler based on the length of the
string.
– NOTE:
• all strings represented by a character array ends with a
special character (the null character ‘\0’)
• A character array representing a string should be defined
large enough to hold the number of characters in the string
+ the termination character
 2003 Prentice Hall, Inc. All rights reserved.
28
Using character arrays to store and
manipulate strings
• One could also use this method to declare strings:
char string1[] = {‘f’, ‘i’, ‘r’, ‘s’, ‘t’, ‘\0’};
If you don’t use ‘\0’, the array would simply
represent an array of characters, not a string!
if you specify the size of string1 and the size of “list
of initializers” is larger  syntax error
• char arrays can be manipulated as other arrays,
example:
– string[0] = ‘f’;
 2003 Prentice Hall, Inc. All rights reserved.
29
Using character arrays to store and
manipulate strings
• Input from keyboard
char string2[ 20 ];
cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
– If too much text entered, data written beyond array
• We want to avoid this
• Printing strings
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found
 2003 Prentice Hall, Inc. All rights reserved.
30
1
// Fig. 7.12: fig07_12.cpp
2
// treating character arrays as strings.
3
#include <iostream>
4
using std::cout;
5
using std::cin;
6
using std::endl;
7
8 int main()
9 {
10
char string1 [20];
// reserve 20 characters
11
char string2 [] = “string literal”; // reserve 15 characters
12
13
// read string from user into array string1
14
cout << “Enter the string “\hello there\”: ”;
15
cin >> string1; // read “hello” [space terminates input]
16
17
// output strings
18
cout << “string1 is: ” << string1 << “\nstring2 is: ” << string2;
19
cout << “\nstring1 with spaces between characters is:\n”;
20
21
22
23
24
25
26
27
28
29
31
Outline
// output characters until null character is reached
for ( int i = 0; string1[ i ]!= ‘\0’; i++ )
cout << string1[ i ] << ‘ ’;
cin >> string1; // reads “there”
cout << “\nstring1 is: ” << string1 <<endl;
return 0; // indicates successful termination
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
Enter the string “hello there”: hello there
string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there
32
Outline
 2003 Prentice Hall, Inc.
All rights reserved.
33
Static and automatic local variables
• Recall static storage
– If static, local variables save values between
function calls
– Visible only in function body
– Can declare local arrays to be static
• Initialized to zero
static int array[3];
• If not static
– Created (and destroyed) in every function call
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 7.13: fig07_13.cpp
// Static arrays are initialized to zero.
#include <iostream>
34
Outline
using std::cout;
using std::endl;
void staticArrayInit( void );
void automaticArrayInit( void );
// function prototype
// function prototype
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << "\n\nSecond call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << endl;
return 0;
// indicates successful termination
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// function to demonstrate a static local array
Static array, initialized to zero
void staticArrayInit( void )
on first function call.
{
// initializes elements to 0 first time function is called
static int array1[ 3 ];
35
Outline
cout << "\nValues on entering staticArrayInit:\n";
// output contents of array1
for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << "
";
Array data is changed; the
modified values stay.
cout << "\nValues on exiting staticArrayInit:\n";
// modify and output
for ( int j = 0; j <
cout << "array1["
<< ( array1[
contents of array1
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
} // end function staticArrayInit
 2003 Prentice Hall, Inc.
All rights reserved.
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// function to demonstrate an automatic local array
void automaticArrayInit( void )
Automatic
{
with every
// initializes elements each time function is called
int array2[ 3 ] = { 1, 2, 3 };
36
array, recreated
function call.
Outline
cout << "\n\nValues on entering automaticArrayInit:\n";
// output contents of array2
for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << "
";
Although the array is
changed, it will be destroyed
when the function exits and
the changes will be lost.
cout << "\nValues on exiting automaticArrayInit:\n";
// modify and output
for ( int j = 0; j <
cout << "array2["
<< ( array2[
contents of array2
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
} // end function automaticArrayInit
 2003 Prentice Hall, Inc.
All rights reserved.
First call to each function:
Values on
array1[0]
Values on
array1[0]
entering staticArrayInit:
= 0 array1[1] = 0 array1[2] = 0
exiting staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
Values on
array2[0]
Values on
array2[0]
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
37
Outline
Second call to each function:
Values on
array1[0]
Values on
array1[0]
entering staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
exiting staticArrayInit:
= 10 array1[1] = 10 array1[2] = 10
Values on
array2[0]
Values on
array2[0]
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
 2003 Prentice Hall, Inc.
All rights reserved.