0% found this document useful (0 votes)
8 views76 pages

Understanding Arrays in Programming

The document provides an overview of arrays as static data structures that hold related data items of the same type and explains their characteristics, including indexing and declaration. It discusses common programming errors related to array indexing and initialization, as well as best practices for defining array sizes using constant variables. Additionally, it includes examples of initializing arrays and summing their elements.

Uploaded by

erensahmet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views76 pages

Understanding Arrays in Programming

The document provides an overview of arrays as static data structures that hold related data items of the same type and explains their characteristics, including indexing and declaration. It discusses common programming errors related to array indexing and initialization, as well as best practices for defining array sizes using constant variables. Additionally, it includes examples of initializing arrays and summing their elements.

Uploaded by

erensahmet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Arrays

© 2006 Pearson Education, Inc. All rights reserved.


2

Introduction

• Arrays
– Data structures containing related data items of same type
– Always remain the same size once created (throughout
program execution)
• Are “static” entities
– Character arrays can also represent strings.

© 2006 Pearson Education, Inc. All rights reserved.


3

Arrays
• Array
– Consecutive (successive) group of memory locations
• All of which have the same type
– Index
• Position number used to refer to a specific location/element
• Also called subscript
• Place in square brackets
– Must be positive integer or integer expression
• First element has index zero
• Example (assume a = 5 and b = 6)
– c[ a + b ] += 2;
• Adds 2 to array element c[ 11 ]
• Subscripted array names (e.g. c[ 7 ] is an lvalue – it can be used on
the left side of the assignment, just as non-array varible names can.

© 2006 Pearson Education, Inc. All rights reserved.


4

Array of 12 elements

© 2006 Pearson Education, Inc. All rights reserved.


5

Arrays (Cont.)

• Examine array c in Figure (previous slide)


– c is the array name
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
– To print sum of the values contained in the first three elements
of arrayc, one can write
• cout << c[0]+ c[1]+c[3] <<endl;
– To divide the value of by 2, and assign the result to the
variable x, one can write
• X= c[5] / 2;
• Brackets used to enclose an array subscript are
actually an operator in C++
© 2006 Pearson Education, Inc. All rights reserved.
6

Common Programming Error


It is important to note the difference between the
“seventh element of the array” and “array
element 7.” Array subscripts begin at 0, so the
“seventh element of the array” has a subscript of 6,
while “array element 7” has a subscript of 7 and is
actually the eighth element of the array.
Unfortunately, this distinction frequently is a source
of off-by-one errors. To avoid such errors, it is good
to refer to specific array elements explicitly by their
array name and subscript number (e.g., c[ 6 ] or
c[ 7 ]).

© 2006 Pearson Education, Inc. All rights reserved.


7

Operators Associativity Type

() [] left to right highest


++ -- static_cast< type >( operand ) left to right unary (postfix)
++ -- + - ! right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma
The operators are shown top to bottom in
decreasing order of precedence with their associativity and type

Operator precedence and associativity.

© 2006 Pearson Education, Inc. All rights reserved.


8

Declaring Arrays

• Declaring an array
– Arrays occupy space in memory
– Programmer specifies type and number of elements
– To tell the compiler to reserve 12 elements for integer
array c , use the declaration
int c[ 12 ];
– Array’s size must be an integer constant greater than zero
– Arrays can be declared to contain values of any non-reference
data type (E.g. An array of type char can be used to store a character string. Otherwise, string object can be used to store character strings. )
– Multiple arrays of the same type can be declared in a single
declaration (E.g. int c[ 12 ], d[ 125 ];)
• Use a comma-separated list of names and sizes

© 2006 Pearson Education, Inc. All rights reserved.


9

Good Programming Practice

We prefer to declare one array per declaration for


readability, modifiability and ease of commenting.

© 2006 Pearson Education, Inc. All rights reserved.


10

Examples Using Arrays

• Using a loop to initialize the array’s elements


– Declare array, specify number of elements
– Use repetition statement to loop for each element
• Use body of repetition statement to initialize each individual
array element

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 11
2 // Initializing an array.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
Declare n as an array of
9
ints with 10 elements
10 int main()
11 {
12 int n[ 10 ]; // n is an array of 10 integers
Each int initialized is to 0
13
14 // initialize elements of array n to 0
15 for ( int i = 0; i < 10; i++ )
16 n[ i ] = 0; // set element at location i to 0
17
18 cout << "Element" << setw( 13 ) << "Value" << endl;

© 2006 Pearson Education,


Inc. All rights reserved.
19 12
20 // output each array element's value
Setw specifies the field width
21 for ( int j = 0; j < 10; j++ )
in which only the next value is to
22 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
be output.
23
24 return 0; // indicates successful termination
25 } // end main

Element Value
0 0 n[ j ] returns int associated
1 0 with index j in array n
2 0
3 0
4 0
5 0
6 0
7 0 Each int has been initialized to 0
8 0
9 0

© 2006 Pearson Education,


Inc. All rights reserved.
13

Examples Using Arrays (Cont.)


• Initializing an array in a declaration with an
initializer list
– Initializer list
• Items enclosed in braces ({})
• Items in list separated by commas
• Example
– int n[] = { 10, 20, 30, 40, 50 };
• Because array size is omitted in the declaration, the
compiler determines the size of the array based on the
size of the initializer list
• Creates a five-element array
• Index values are 0, 1, 2, 3, 4
• Initialized to values 10, 20, 30, 40, 50, respectively

© 2006 Pearson Education, Inc. All rights reserved.


14

Examples Using Arrays (Cont.)

• Initializing an array in a declaration with an


initializer list (Cont.)
– If fewer initializers than elements in the array
• Remaining elements are initialized to zero
• Example
– int n[ 10 ] = { 0 };
• Explicitly initializes first element to zero
• Implicitly initializes remaining nine elements to zero
– If more initializers than elements in the array
• Compilation error

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 15
2 // Initializing an array in a declaration.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw; Declare n as an array of ints
9
10 int main() Compiler uses initializer
11 { list to initialize array
12 // use initializer list to initialize array n
13 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
14
15 cout << "Element" << setw( 13 ) << "Value" << endl;

© 2006 Pearson Education,


Inc. All rights reserved.
16 16
17 // output each array element's value
18 for ( int i = 0; i < 10; i++ )
19 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
20
21 return 0; // indicates successful termination
22 } // end main

Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37

© 2006 Pearson Education,


Inc. All rights reserved.
17

Common Programming Error

Providing more initializers in an array initializer


list than there are elements in the array is a
compilation error.

© 2006 Pearson Education, Inc. All rights reserved.


18

Common Programming Error

Forgetting to initialize the elements of an array


whose elements should be initialized is a logic error.

© 2006 Pearson Education, Inc. All rights reserved.


19

Examples Using Arrays (Cont.)

• Specifying an array’s size with a constant variable


and setting array elements with calculations
– Initialize elements of 10-element array to even integers
(greater than zero)
– Use repetition statement that calculates value for current
element, initializes array element using calculated value

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time.
20
2 // Set array s to the even integers from 2 to 20.
3 #include <iostream>
4 using std::cout;
5 using std::endl; arraySize
Declare constant variable
6 using the const keyword
7 #include <iomanip>
8 using std::setw; When arraySize is simply chaged
9 to 1000 the first for will fill 1000-
10 int main()
element of array
11 {
12 // constant variable can be used to specify array size
13 const int arraySize = 10; Declare array that contains 10 ints
14
15 int s[ arraySize ]; // array s has 10 elements
16
17 for ( int i = 0; i < arraySize; i++ ) // set the values
18 s[ i ] = 2 + 2 * i;

Use array index to assign element’s value

© 2006 Pearson Education,


Inc. All rights reserved.
19
21
20 cout << "Element" << setw( 13 ) << "Value" << endl;
21
22 // output contents of array s in tabular format
23 for ( int j = 0; j < arraySize; j++ )
24 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
25
26 return 0; // indicates successful termination
27 } // end main

Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20

© 2006 Pearson Education,


Inc. All rights reserved.
22

Examples Using Arrays (Cont.)

• Constant variables
– Declared using the const qualifier
– Also called name constants or read-only variables
– Must be initialized with a constant expression when they are
declared and cannot be modified thereafter
– Can be placed anywhere a constant expression is expected
– Using constant variables to specify array sizes makes
programs more scalable and eliminates “magic numbers”

© 2006 Pearson Education, Inc. All rights reserved.


23

Common Programming Error

Not assigning a value to a constant variable


when it is declared is a compilation error.

© 2006 Pearson Education, Inc. All rights reserved.


24

Common Programming Error

Assigning a value to a constant variable in an


executable statement is a compilation error.

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 25
2 // Using a properly initialized constant variable.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main() Declaring constant value
8 {
9 const int x = 7; // initialized constant variable
10
11 cout << "The value of constant variable x is: " << x << endl;
12
13 return 0; // indicates successful termination
14 } // end main

The value of constant variable x is: 7

© 2006 Pearson Education,


Inc. All rights reserved.
1 // Name Surname, Date, Time.
26
2 // A const variable must be initialized.
3
4 int main()
Must initialize a constant at the time of declaration
5 {
6 const int x; // Error: x must be initialized
7 Cannot modify a constant
8 x = 7; // Error: cannot modify a const variable
9
10 return 0; // indicates successful termination
11 } // end main
Borland C++ command-line compiler error message:

Error E2304 fig07_07.cpp 6: Constant variable 'x' must be initialized


in function main()
Error E2024 fig07_07.cpp 8: Cannot modify a const object in function main()

Microsoft Visual C++.NET compiler error message:

C:\cpphtp5_examples\ch07\fig07_07.cpp(6) : error C2734: 'x' : const object


must be initialized if not extern
C:\cpphtp5_examples\ch07\fig07_07.cpp(8) : error C2166: l-value specifies
const object

GNU C++ compiler error message:

fig07_07.cpp:6: error: uninitialized const `x'


fig07_07.cpp:8: error: assignment of read-only variable `x'
Error messages differ based
on the compiler

© 2006 Pearson Education,


Inc. All rights reserved.
27

Common Programming Error

Only constants can be used to declare the size of


automatic and static arrays. Not using a constant for
this purpose is a compilation error.

© 2006 Pearson Education, Inc. All rights reserved.


28

Software Engineering Observation

Defining the size of each array as a constant


variable instead of a literal constant can make
programs more scalable.

© 2006 Pearson Education, Inc. All rights reserved.


29

Good Programming Practice

Defining the size of an array as a constant variable


instead of a literal constant makes programs clearer.
This technique eliminates so-called magic numbers.
•For example, repeatedly mentioning the size 10 in array-
processing code for a 10-element array gives the number 10 an
artificial significance and can unfortunately confuse the reader
when the program includes other 10s that have nothing to do with
the array size.

© 2006 Pearson Education, Inc. All rights reserved.


30

Examples Using Arrays (Cont.)

• Summing the elements of an array


– Array elements can represent a series of values
• We can sum these values
• Use repetition statement to loop through each element
– Add element value to a total

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 31
2 // Compute the sum of the elements of the array.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
To initialize the array, you can also use :
6 for ( int j = 0; j < arraySize; j++ )
7 int main() cin >> a[j];
8 {
9 const int arraySize = 10; // constant variable indicating size of array
10 int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
11 int total = 0;
12
Declare array with initializer list
13 // sum contents of array a
14 for ( int i = 0; i < arraySize; i++ )
15 total += a[ i ];
16
Sum all array values
17 cout << "Total of array elements: " << total << endl;
18
19 return 0; // indicates successful termination
20 } // end main

Total of array elements: 849

© 2006 Pearson Education,


Inc. All rights reserved.
32

Examples Using Arrays (Cont.)

• Using bar charts to display array data


graphically
– Present data in graphical manner
• E.g., bar chart
– Examine the distribution of grades
– Nested for statement used to output bars
– Suppose that the students MT1 grades are following 87, 68,
94, 100, 83, 78, 85, 91, 76, 87. There are one grade of 100,
two grades in 90s, four grades in 80s, two grades in 70s, one
grades in 60s and no grades below 60.

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 33
2 // Bar chart printing program.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 int main()
11 {
12 const int arraySize = 11;
13 int n[ arraySize ] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };
14
15 cout << "Grade distribution:" << endl;
16
Declare array with initializer list
17 // for each element of array n, output a bar of the chart
18 for ( int i = 0; i < arraySize; i++ )
19 {
20 // output bar labels ("0-9:", ..., "90-99:", "100:" )
21 if ( i == 0 )
22 cout << " 0-9: ";
23 else if ( i == 10 )
24 cout << " 100: ";
25 else
26 cout << i * 10 << "-" << ( i * 10 ) + 9 << ": ";

© 2006 Pearson Education,


Inc. All rights reserved.
27
34
28 // print bar of asterisks
29 for ( int stars = 0; stars < n[ i ]; stars++ )
30 cout << '*';
For each array element, print the
31 associated number of asterisks
32 cout << endl; // start a new line of output
33 } // end outer for
34
35 return 0; // indicates successful termination
36 } // end main

Grade distribution:
0-9:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *

© 2006 Pearson Education,


Inc. All rights reserved.
35

Common Programming Error

Although it is possible to use the same control


variable in a for statement and a second for
statement nested inside, this is confusing and can
lead to logic errors.

© 2006 Pearson Education, Inc. All rights reserved.


36

Examples Using Arrays (Cont.)

• Using the elements of an array as counters


– Use a series of counter variables to summarize data
– Counter variables make up an array
– Store frequency values

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time.
37
2 // Roll a six-sided die 6,000,000 times.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 #include <cstdlib>
11 using std::rand;
12 using std::srand;
13
14 #include <ctime>
15 using std::time;
16
17 int main() Declare frequency as array of 7 ints
18 {
19 const int arraySize = 7; // ignore element zero
20 int frequency[ arraySize ] = { 0 };
21
22 srand( time( 0 ) ); // seed random number generator
23 Generate 6000000 random
24 // roll die 6,000,000 times; use die value as frequency index integers in range 1 to 6
25 for ( int roll = 1; roll <= 6000000; roll++ )
26 frequency[ 1 + rand() % 6 ]++;
Increment frequency values at the
index associated with the random number

© 2006 Pearson Education,


Inc. All rights reserved.
27 38
28 cout << "Face" << setw( 13 ) << "Frequency" << endl;
29
30 // output each array element's value
31 for ( int face = 1; face < arraySize; face++ )
32 cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ]
33 << endl;
34
35 return 0; // indicates successful termination
36 } // end main

Face Frequency
1 1000167
2 1000149
3 1000152
4 998748
5 999626
6 1001158

© 2006 Pearson Education,


Inc. All rights reserved.
39

Examples Using Arrays (Cont.)

• Using arrays to summarize survey results


– 40 students rate the quality of food
• 1-10 rating scale: 1 means awful, 10 means excellent
– Place 40 responses in an array of integers
– Summarize results
– Each element of the array used as a counter for one of the
survey responses
• C++ has no array bounds (limits) checking
– Does not prevent the computer from referring to an element
that does not exist
• Could lead to serious execution-time errors

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time.
40
2 // Student survey program.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 int main() Array responses will
11 {
store 40 responses
12 // define array sizes
13 const int responseSize = 40; // size of array responses
14 const int frequencySize = 11; // size of array frequency
Array frequency will contain 11
15
16 // place survey responses in array responses
ints (ignore the first element)
17 const int responses[ responseSize ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8,
18 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7,
19 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
20
Initialize responses
21 // initialize frequency counters to 0 with 40 responses
22 int frequency[ frequencySize ] = { 0 };
23 Initialize frequency to all 0s
24 // for each answer, select responses element and use that value
25 // as frequency subscript to determine element to increment
26 for ( int answer = 0; answer < responseSize; answer++ ) For each response, increment
27 frequency[ responses[ answer ] ]++; frequency value at the index
28 associated with that response
29 cout << "Rating" << setw( 17 ) << "Frequency" << endl;

© 2006 Pearson Education,


Inc. All rights reserved.
30 41
31 // output each array element's value
32 for ( int rating = 1; rating < frequencySize; rating++ )
33 cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ]
34 << endl;
35
36 return 0; // indicates successful termination
37 } // end main

Rating Frequency
1 2
2 2
3 2
4 2
5 5
6 11
7 5
8 7
9 1
10 3

© 2006 Pearson Education,


Inc. All rights reserved.
42

Common Programming Error

Referring to an element outside the array bounds is


an execution-time logic error. It is not a syntax
error.

© 2006 Pearson Education, Inc. All rights reserved.


43

Error-Prevention Tip

When looping through an array, the array


subscript should never go below 0 and should
always be less than the total number of elements
in the array (one less than the size of the array).
Make sure that the loop-termination condition
prevents accessing elements outside this range.

© 2006 Pearson Education, Inc. All rights reserved.


44

Portability Tip

The (normally serious) effects of referencing


elements outside the array bounds are system
dependent. Often this results in changes to the
value of an unrelated variable or a fatal error that
terminates program execution.

© 2006 Pearson Education, Inc. All rights reserved.


45

Examples Using Arrays (Cont.)

• Using character arrays to store and manipulate


strings
– Arrays may be of any type, including chars
• We can store character strings in char arrays
– Can be initialized using a string literal
• Example
– char string1[] = "Hi";
• Equivalent to
– char string1[] = { 'H', 'i', '\0' };
– Note the use of single quotes to define each character constant.
– Array contains each character plus a special string-termination character
called the null character ('\0'). (All character arrays representing
strings ends with this character) (Without it, a character array would
simply represent an array of characters, not a string.)

© 2006 Pearson Education, Inc. All rights reserved.


46

Examples Using Arrays (Cont.)

• Using character arrays to store and manipulate


strings (Cont.)
– Can also be initialized with individual character constants in an
initializer list
char string1[] =
{ 'f', 'i', 'r', 's', 't', '\0' };
– Can also input a string directly into a character array from the
keyboard using cin and >>
cin >> string1;
• cin >> may read more characters than the array can store
– A character array representing a null-terminated string can be output
with cout and <<
– cin and cout do not provide similar input and output processing
capabilities for other array types !!!

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 47
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 ]; // reserves 20 characters
11 char string2[] = "string literal"; // reserves 15 characters
12
13 // read string from user into array string1 Store "string literal"
14 cout << "Enter the string \"hello there\": "; as an array of characters
15 cin >> string1; // reads "hello" [space terminates input]
16 Initializing an array of
17 // output strings characters using cin
18 cout << "string1 is: " << string1 << "\nstring2 is: " << string2;
19
20 cout << "\nstring1 with spaces between characters is:\n";
21

Output array using cin

© 2006 Pearson Education,


Inc. All rights reserved.
22 // output characters until null character is reached
48
23 for ( int i = 0; string1[ i ] != '\0'; i++ )
24 cout << string1[ i ] << ' '; Loop until the terminating
25
null character is reached
26 cin >> string1; // reads "there"
27 cout << "\nstring1 is: " << string1 << endl;
28 Accessing specific
29 return 0; // indicates successful termination characters in the array
30 } // end main

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

© 2006 Pearson Education,


Inc. All rights reserved.
49

Examples Using Arrays (Cont.)

•static local arrays and automatic local arrays


– A static local variable in a function
• Exists for the duration of the program
• But is visible only in the function body
– A static local array
• Exists for the duration of the program
• Is initialized when its declaration is first encountered
– All elements are initialized to zero if not explicitly
initialized
• This does not happen for automatic local arrays
(Recall that C++ does not perform such default
initialization for automatic variables)

© 2006 Pearson Education, Inc. All rights reserved.


50

Performance Tip

We can apply static to a local array


declaration so that the array is not created and
initialized each time the program calls the
function and is not destroyed each time the
function terminates in the program. This can
improve performance, especially when using
large arrays.

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 51
2 // Static arrays are initialized to zero.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 void staticArrayInit( void ); // function prototype
8 void automaticArrayInit( void ); // function prototype
9
10 int main()
11 {
12 cout << "First call to each function:\n";
13 staticArrayInit();
14 automaticArrayInit();
15
16 cout << "\n\nSecond call to each function:\n";
17 staticArrayInit();
18 automaticArrayInit();
19 cout << endl;
20
21 return 0; // indicates successful termination
22 } // end main

© 2006 Pearson Education,


Inc. All rights reserved.
23
52
24 // function to demonstrate a static local array
25 void staticArrayInit( void )
26 {
27 // initializes elements to 0 first time function is called
28 static int array1[ 3 ]; // static local array
29
30 cout << "\nValues on entering staticArrayInit:\n";
Create a static array
31
using keyword static
32 // output contents of array1
33 for ( int i = 0; i < 3; i++ )
34 cout << "array1[" << i << "] = " << array1[ i ] << " ";
35
36 cout << "\nValues on exiting staticArrayInit:\n";
37
38 // modify and output contents of array1
39 for ( int j = 0; j < 3; j++ )
40 cout << "array1[" << j << "] = " << ( array1[ j ] += 5 ) << " ";
41 } // end function staticArrayInit
42
43 // function to demonstrate an automatic local array
44 void automaticArrayInit( void )
45 {
46 // initializes elements each time function is called
47 int array2[ 3 ] = { 1, 2, 3 }; // automatic local array
48
49 cout << "\n\nValues on entering automaticArrayInit:\n";
Create an automatic local array

© 2006 Pearson Education,


Inc. All rights reserved.
50
53
51 // output contents of array2
52 for ( int i = 0; i < 3; i++ )
53 cout << "array2[" << i << "] = " << array2[ i ] << " ";
54
55 cout << "\nValues on exiting automaticArrayInit:\n";
56
57 // modify and output contents of array2
58 for ( int j = 0; j < 3; j++ )
59 cout << "array2[" << j << "] = " << ( array2[ j ] += 5 ) << " ";
60 } // end function automaticArrayInit

First call to each function:

Values on entering staticArrayInit:


array1[0] = 0 array1[1] = 0 array1[2] = 0
Values on exiting staticArrayInit:
array1[0] = 5 array1[1] = 5 array1[2] = 5

Values on entering automaticArrayInit:


array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

Second call to each function:

Values on entering staticArrayInit:


array1[0] = 5 array1[1] = 5 array1[2] = 5
Values on exiting staticArrayInit:
Values reflect changes from the previous
array1[0] = 10 array1[1] = 10 array1[2] = 10 function call – the array was not reinitialized
Values on entering automaticArrayInit:
array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

© 2006 Pearson Education,


Inc. All rights reserved.
54

Common Programming Error

Assuming that elements of a function’s local


static array are initialized every time the
function is called can lead to logic errors in a
program.

© 2006 Pearson Education, Inc. All rights reserved.


55

Passing Arrays to Functions

• To pass an array argument to a function


– Specify array name without brackets
• If array hourlyTemperatures is declared as
int hourlyTemperatures[ 24 ];
• The function call
modifyArray( hourlyTemperatures, 24 );
passes array hourlyTemperatures and its size to function
modifyArray
– Array size is normally passed as another argument so the
function can process the specific number of elements in the
array

© 2006 Pearson Education, Inc. All rights reserved.


56

Passing Arrays to Functions (Cont.)

• Arrays are passed by reference


– Function call actually passes starting address of array
(The value of the name of the array is the address in the
computer’s memory of the first element of the array)
• So function knows where array is located in memory
– Caller gives called function direct access to caller’s data
• Called function can manipulate this data ( The called
funtions can modify the element values in the caller’s original
array.)

© 2006 Pearson Education, Inc. All rights reserved.


57

Performance Tip

Passing arrays by reference makes sense for


performance reasons. If arrays were passed by
value, a copy of each element would be passed. For
large, frequently passed arrays, this would be time
consuming and would require considerable
storage for the copies of the array elements.

© 2006 Pearson Education, Inc. All rights reserved.


58

Passing Arrays to Functions (Cont.)

• Individual array elements passed by value


– Single pieces of data
• Known as scalars or scalar quantities
– To pass an element to a function
• Use the subscripted name of the array element as an
argument
• Functions that take arrays as arguments
– Function parameter list must specify array parameter
• Example (of function header for a function modArray)
– void modArray( int b[], int arraySize );

© 2006 Pearson Education, Inc. All rights reserved.


59

Passing Arrays to Functions (Cont.)

• Functions that take arrays as arguments (Cont.)


– Array parameter may include the size of the array
(between the brackets [ ])
• Compiler will ignore it, though
– Compiler only cares about the address of the first
element
• Function prototypes may include parameter
names
– But the compiler will ignore them
– Parameter names may be left out of function prototypes

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time.
60
2 // Passing arrays and individual array elements to functions.
3 #include <iostream>
Can also be written as following but the compiler ignores variable names in
4 using std::cout;
5 using std::endl;
prototypes:
6 void modifyArray( int anyArrayName[], int anyArrayVariable);
7 #include <iomanip>
8 using std::setw;
9 Function takes an array as argument
10 void modifyArray( int [], int ); // appears strange.
11 void modifyElement( int );
12
13 int main()
Declare 5-int array array with initializer list
14 {
15 const int arraySize = 5; // size of array a
16 int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a
17
18 cout << "Effects of passing entire array by reference:"
19 << "\n\nThe values of the original array are:\n";
20
21 // output original array elements
22 for ( int i = 0; i < arraySize; i++ )
23 cout << setw( 3 ) << a[ i ];
24
25 cout << endl;
26
27 // pass array a to modifyArray by reference
28 modifyArray( a, arraySize ); Pass entire array to function
29 cout << "The values of the modified array are:\n"; modifyArray

© 2006 Pearson Education,


Inc. All rights reserved.
30
61
31 // output modified array elements
32 for ( int j = 0; j < arraySize; j++ )
33 cout << setw( 3 ) << a[ j ];
34
35 cout << "\n\n\nEffects of passing array element by value:"
Pass array element a[ 3 ] to
36 << "\n\na[3] before modifyElement: " << a[ 3 ] << endl;
37 function modifyElement
38 modifyElement( a[ 3 ] ); // pass array element a[ 3 ] by value
39 cout << "a[3] after modifyElement: " << a[ 3 ] << endl;
40
41 return 0; // indicates successful termination
42 } // end main
43
44 // in function modifyArray, "b" points to the original array "a" in memory
45 void modifyArray( int b[], int sizeOfArray )
46 { Function modifyArray
47 // multiply each array element by 2 manipulates the array directly
48 for ( int k = 0; k < sizeOfArray; k++ )
49 b[ k ] *= 2;
50 } // end function modifyArray

© 2006 Pearson Education,


Inc. All rights reserved.
51 62
52 // in function modifyElement, "e" is a local copy of
53 // array element a[ 3 ] passed from main
54 void modifyElement( int e )
Function modifyElement
55 { manipulates array element’s copy
56 // multiply parameter by 2
57 cout << "Value of element in modifyElement: " << ( e *= 2 ) << endl;
58 } // end function modifyElement

Effects of passing entire array by reference:

The values of the original array are:


0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element by value:

a[3] before modifyElement: 6


Value of element in modifyElement: 12
a[3] after modifyElement: 6

© 2006 Pearson Education,


Inc. All rights reserved.
63

Passing Arrays to Functions (Cont.)

•const array parameters


– Qualifier const
– Prevent modification of array values in the caller by code
in the called function
– Elements in the array are constant in the function body
– Enables programmer to prevent accidental modification of
data

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time. 64
2 // Demonstrating the const type qualifier.
3 #include <iostream> Using const to prevent the
4 using std::cout; function from modifying the array
5 using std::endl;
6
7 void tryToModifyArray( const int [] ); // function prototype
8
9 int main()
Array a will be const when in
10 {
11 int a[] = { 10, 20, 30 };
the body of the function
12
13 tryToModifyArray( a );
14 cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';
15
16 return 0; // indicates successful termination
17 } // end main
18

© 2006 Pearson Education,


Inc. All rights reserved.
19 // In function tryToModifyArray, "b" cannot be used 65
20 // to modify the original array "a" in main.
21 void tryToModifyArray( const int b[] )
22 {
23 b[ 0 ] /= 2; // error
Array cannot be modified; it is
24 b[ 1 ] /= 2; // error
const within the body function
25 b[ 2 ] /= 2; // error
26 } // end function tryToModifyArray
Borland C++ command-line compiler error message:

Error E2024 fig07_15.cpp 23: Cannot modify a const object


in function tryToModifyArray(const int * const)
Error E2024 fig07_15.cpp 24: Cannot modify a const object
in function tryToModifyArray(const int * const)
Error E2024 fig07_15.cpp 25: Cannot modify a const object
in function tryToModifyArray(const int * const)

Microsoft Visual C++.NET compiler error message:

C:\cpphtp5_examples\ch07\fig07_15.cpp(23) : error C2166: l-value specifies


const object
C:\cpphtp5_examples\ch07\fig07_15.cpp(24) : error C2166: l-value specifies
const object
C:\cpphtp5_examples\ch07\fig07_15.cpp(25) : error C2166: l-value specifies
const object

GNU C++ compiler error message:

fig07_15.cpp:23: error: assignment of read-only location


fig07_15.cpp:24: error: assignment of read-only location
fig07_15.cpp:25: error: assignment of read-only location

© 2006 Pearson Education,


Inc. All rights reserved.
66

Common Programming Error

Forgetting that arrays in the caller are passed by


reference, and hence can be modified in called
functions, may result in logic errors.

© 2006 Pearson Education, Inc. All rights reserved.


67

Software Engineering Observation

Applying the const type qualifier to an array


parameter in a function definition to prevent
the original array from being modified in the
function body is another example of the principle
of least privilege. Functions should not be given
the capability to modify an array unless it is
absolutely necessary.

© 2006 Pearson Education, Inc. All rights reserved.


68

Multidimensional Array

• Multidimensional arrays with two dimensions


– Called two dimensional or 2-D arrays
– Represent tables of values with rows and columns
– Elements referenced with two subscripts ([ x ][ y ])
– In general, an array with m rows and n columns is called an
m-by-n array
• Multidimensional arrays can have more than two
dimensions

© 2006 Pearson Education, Inc. All rights reserved.


69

Common Programming Error

Referencing a two-dimensional array element


a[ x ][ y ] incorrectly as a[ x, y ] is an
error. Actually, a[ x, y ] is treated as
a[ y ], because C++ evaluates the expression
x, y (containing a comma operator) simply as y
(the last of the comma-separated expressions).

© 2006 Pearson Education, Inc. All rights reserved.


70

Multidimensional Array (Cont.)

• Declaring and initializing two-dimensional arrays


– Declaring two-dimensional array b
• int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ]
– 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ]
• int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
– Row 0 contains values 1 and 0 (implicitly initialized to
zero)
– Row 1 contains values 3 and 4

© 2006 Pearson Education, Inc. All rights reserved.


71

Two-dimensional array with three rows and four columns.

© 2006 Pearson Education, Inc. All rights reserved.


1 // Name Surname, Date, Time.
72
2 // Initializing multidimensional arrays.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 void printArray( const int [][ 3 ] ); // prototype
8
9 int main()
10 {
11 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
12 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; Use nested array initializers
13 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; to initialize arrays
14
15 cout << "Values in array1 by row are:" << endl;
16 printArray( array1 );
17
18 cout << "\nValues in array2 by row are:" << endl;
19 printArray( array2 );
20
21 cout << "\nValues in array3 by row are:" << endl;
22 printArray( array3 );
23 return 0; // indicates successful termination
24 } // end main

© 2006 Pearson Education,


Inc. All rights reserved.
25
73
26 // output array with two rows and three columns
27 void printArray( const int a[][ 3 ] )
28 {
29 // loop through array's rows
30 for ( int i = 0; i < 2; i++ )
31 {
32 // loop through columns of current row
33 for ( int j = 0; j < 3; j++ ) Use nested for loops to print array
34 cout << a[ i ][ j ] << ' ';
35
36 cout << endl; // start new line of output
37 } // end outer for
38 } // end function printArray

Values in array1 by row are:


1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0

© 2006 Pearson Education,


Inc. All rights reserved.
74

Multidimensional Array (Cont.)


• Multidimensional array parameters
– Size of first dimension is not required
• As with a one-dimensional array
– Size of subsequent dimensions are required
• Compiler must know how many elements to skip to move to the second
element in the first dimension
– Example
• void printArray( const int a[][ 3 ] );
– Function will skip row 0’s 3 elements to access row 1’s elements
(a[ 1 ][ x ])

© 2006 Pearson Education, Inc. All rights reserved.


75

Multidimensional Array (Cont.)


• Multidimensional-array manipulations
– Commonly performed with for statements
• Example
– Modify all elements in a row
• for ( int col = 0; col < 4; col++ )
a[ 2 ][ col ] = 0;
• Example
– Total all elements
• total = 0;
for ( row = 0; row < 3; row++ )
for ( col = 0; col < 4; col++ )
total += a[ row ][ col ];

© 2006 Pearson Education, Inc. All rights reserved.


76

© 2006 Pearson Education, Inc. All rights reserved.

You might also like