0% found this document useful (0 votes)
60 views96 pages

Arrays and Vectors: 2006 Pearson Education, Inc. All Rights Reserved

The document discusses arrays in C++. It defines arrays as data structures that contain related data items of the same type. Arrays have a fixed size once created. The document covers declaring and initializing arrays, including using initializer lists, passing arrays to functions, and searching and sorting array elements. Multidimensional arrays and the C++ vector class are also introduced.

Uploaded by

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

Arrays and Vectors: 2006 Pearson Education, Inc. All Rights Reserved

The document discusses arrays in C++. It defines arrays as data structures that contain related data items of the same type. Arrays have a fixed size once created. The document covers declaring and initializing arrays, including using initializer lists, passing arrays to functions, and searching and sorting array elements. Multidimensional arrays and the C++ vector class are also introduced.

Uploaded by

SEENIVAS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 96

1

Arrays and Vectors

 2006 Pearson Education, Inc. All rights reserved.


2

7.1 Introduction
7.2 Arrays
7.3 Declaring Arrays
7.4 Examples Using Arrays
7.5 Passing Arrays to Functions
7.6 Case Study: Class GradeBook Using an Array to Store Grades
7.7 Searching Arrays with Linear Search
7.8 Sorting Arrays with Insertion Sort
7.9 Multidimensional Arrays
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array
7.11 Introduction to C++ Standard Library Class Template vector
7.12 (Optional) Software Engineering Case Study: Collaboration
Among Objects in the ATM System
7.13 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved.


3

7.1 Introduction
• Arrays
– Data structures containing related data items of same type
– Always remain the same size once created
• Are “static” entities
– Character arrays can also represent strings
– C-style pointer-based arrays vs. vectors (object-based)
• Vectors are safer and more versatile

 2006 Pearson Education, Inc. All rights reserved.


4

7.2 Arrays
• Array
– Consecutive 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 ]

 2006 Pearson Education, Inc. All rights reserved.


5

Fig.7.1 | Array of 12 elements

 2006 Pearson Education, Inc. All rights reserved.


6

7.2 Arrays (Cont.)


• Examine array c in Fig. 7.1
– c is the array name
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
• Brackets used to enclose an array subscript are
actually an operator in C++

 2006 Pearson Education, Inc. All rights reserved.


7

7.3 Declaring Arrays


• Declaring an array
– Arrays occupy space in memory
– Programmer specifies type and number of elements
• Example
– int c[ 12 ];
• c is an array of 12 ints
– Array’s size must be an integer constant greater than zero
– Arrays can be declared to contain values of any non-
reference data type
– Multiple arrays of the same type can be declared in a single
declaration
• Use a comma-separated list of names and sizes

 2006 Pearson Education, Inc. All rights reserved.


8

7.4 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 // Fig. 7.3: fig07_03.cpp
9
2 // Initializing an array.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_03.cpp
7 #include <iomanip>
8 using std::setw; (1 of 2)
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
10
20 // output each array element's value
Outline
21 for ( int j = 0; j < 10; j++ )
22 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
23
24 return 0; // indicates successful termination fig07_03.cpp
25 } // end main
(2 of 2)
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 Each int has been initialized to 0
7 0
8 0
9 0

 2006 Pearson Education,


Inc. All rights reserved.
11

7.4 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.


12

7.4 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 // Fig. 7.4: fig07_04.cpp
13
2 // Initializing an array in a declaration.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_04.cpp
7 #include <iomanip>
8 using std::setw; Declare n as an array of ints (1 of 2)
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
14
17 // output each array element's value
Outline
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 fig07_04.cpp
22 } // end main
(2 of 2)
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.
15

7.4 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
– Use repetition statement that calculates value for current
element, initializes array element using calculated value

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.5: fig07_05.cpp
16
2
3
// Set array s to the even integers from 2 to 20.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig07_05.cpp
7 #include <iomanip>
8 using std::setw;
(1 of 2)
9 Declare constant variable arraySize
10 int main() using the const keyword
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
17
20
21
cout << "Element" << setw( 13 ) << "Value" << endl;
Outline
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;
fig07_05.cpp
25
26 return 0; // indicates successful termination
27 } // end main
(2 of 2)
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.
18

7.4 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.


1 // Fig. 7.6: fig07_06.cpp
19
2 // Using a properly initialized constant variable.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_06.cpp
7 int main() Declaring constant value
8 { (1 of 1)
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 // Fig. 7.7: fig07_07.cpp
20
2
3
// A const variable must be initialized.
Outline
4 int main()
Must initialize a constant at the time of declaration
5 {
6 const int x; // Error: x must be initialized
fig07_07.cpp
7 Cannot modify a constant
8 x = 7; // Error: cannot modify a const variable
9
(1 of 1)
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' Error messages differ based


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

 2006 Pearson Education,


Inc. All rights reserved.
21

7.4 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 // Fig. 7.8: fig07_08.cpp
22
2 // Compute the sum of the elements of the array.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_08.cpp
7 int main()
8 { (1 of 1)
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.
23

7.4 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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.9: fig07_09.cpp
24
2 // Bar chart printing program.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_09.cpp
7 #include <iomanip>
8 using std::setw; (1 of 2)
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
25
28
29
// print bar of asterisks
for ( int stars = 0; stars < n[ i ]; stars++ )
Outline
30 cout << '*';
31
32 For
cout << endl; // start a new line of outputeach array element, print the
fig07_09.cpp
33 } // end outer for associated number of asterisks
34
35 return 0; // indicates successful termination
(2 of 2)
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.
26

7.4 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 // Fig. 7.10: fig07_10.cpp
27
2
3
// Roll a six-sided die 6,000,000 times.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig07_10.cpp
7 #include <iomanip>
8 using std::setw;
9
(1 of 2)
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
28
28 cout << "Face" << setw( 13 ) << "Frequency" << endl;
Outline
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 ] fig07_10.cpp
33 << endl;
34 (2 of 2)
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.
29

7.4 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 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 // Fig. 7.11: fig07_11.cpp
30
2
3
// Student poll program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig07_11.cpp
7 #include <iomanip>
8 using std::setw;
9
(1 of 2)
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
15
Array frequency will contain 11
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 };
Initialize responses
20
with 40 responses
21 // initialize frequency counters to 0
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++ )
27 frequency[ responses[ answer ] ]++;
28 For each response, increment
29 cout << "Rating" << setw( 17 ) << "Frequency" << frequency value at the index
endl;
associated with that response
 2006 Pearson Education,
Inc. All rights reserved.
30
31
31 // output each array element's value
Outline
32 for ( int rating = 1; rating < frequencySize; rating++ )
33 cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ]
34 << endl;
35 fig07_11.cpp
36 return 0; // indicates successful termination
37 } // end main (2 of 2)
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.
32

Good Programming Practice 7.3

Strive for program clarity. It is sometimes


worthwhile to trade off the most efficient use
of memory or processor time in favor of
writing clearer programs.

 2006 Pearson Education, Inc. All rights reserved.


33

Common Programming Error 7.8

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.


34

7.4 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' };
– Array contains each character plus a special string-
termination character called the null character ('\0')

 2006 Pearson Education, Inc. All rights reserved.


35

7.4 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 <<

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.12: fig07_12.cpp
36
2 // Treating character arrays as strings.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl; fig07_12.cpp
7
8 int main() (1 of 2)
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
37
23
24
for ( int i = 0; string1[ i ] != '\0'; i++ )
Outline
cout << string1[ i ] << ' '; Loop until the terminating
25
null character is reached
26 cin >> string1; // reads "there"
27 cout << "\nstring1 is: " << string1 << endl;
fig07_12.cpp
28 Accessing specific
29 return 0; // indicates successful termination characters in the array (2 of 2)
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.
38

7.4 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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.13: fig07_13.cpp
39
2 // Static arrays are initialized to zero.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig07_13.cpp
7 void staticArrayInit( void ); // function prototype
8 void automaticArrayInit( void ); // function prototype (1 of 3)
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
40
24 // function to demonstrate a static local array
25 void staticArrayInit( void )
Outline
26 {
27 // initializes elements to 0 first time function is called
28 static int array1[ 3 ]; // static local array
fig07_13.cpp
29
30 cout << "\nValues on entering staticArrayInit:\n";
Create a static
(2 of 3) array
31
32 // output contents of array1
using keyword static
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
41
51
52
// output contents of array2
for ( int i = 0; i < 3; i++ )
Outline
53 cout << "array2[" << i << "] = " << array2[ i ] << " ";
54
55 cout << "\nValues on exiting automaticArrayInit:\n";
fig07_13.cpp
56
57 // modify and output contents of array2
58 for ( int j = 0; j < 3; j++ )
(3 of 3)
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.
42

7.5 Passing Arrays to Functions


• To pass an array argument to a function
– Specify array name without brackets
• 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.


43

7.5 Passing Arrays to Functions (Cont.)

• Arrays are passed by reference


– Function call actually passes starting address of 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

 2006 Pearson Education, Inc. All rights reserved.


44

7.5 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
– void modArray( int b[], int arraySize );

 2006 Pearson Education, Inc. All rights reserved.


45

7.5 Passing Arrays to Functions (Cont.)

• Functions that take arrays as arguments (Cont.)


– Array parameter may include the size of the array
• 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 // Fig. 7.14: fig07_14.cpp
46
2
3
// Passing arrays and individual array elements to functions.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl; Function takes an array as argument
6
fig07_14.cpp
7 #include <iomanip>
8 using std::setw;
9
(1 of 3)
10 void modifyArray( int [], int ); // appears strange
11 void modifyElement( int );
12
Declare 5-int array array with initializer list
13 int main()
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
47
31
32
// output modified array elements
for ( int j = 0; j < arraySize; j++ )
Outline
33 cout << setw( 3 ) << a[ j ];
34
35 cout << "\n\n\nEffects of passing array element by value:"
36 << "\n\na[3] before modifyElement: " << a[ 3 ] << endl;
Pass array element a[ 3 ] to
fig07_14.cpp
37 function modifyElement
38 modifyElement( a[ 3 ] ); // pass array element a[ 3 ] by value
(2 of 3)
39 cout << "a[3] after modifyElement: " << a[ 3 ] << endl;
40
41 return 0; // indicates successful termination
42 } // end main
43
Function
44 // in function modifyArray, "b" points to the original array "a" modifyArray
in memory
45 void modifyArray( int b[], int sizeOfArray ) manipulates the array directly
46 {
47 // multiply each array element by 2
48 for ( int k = 0; k < sizeOfArray; k++ )
49 b[ k ] *= 2;
50 } // end function modifyArray

 2006 Pearson Education,


Inc. All rights reserved.
51
48
52 // in function modifyElement, "e" is a local copy of
Outline
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 fig07_14.cpp
57 cout << "Value of element in modifyElement: " << ( e *= 2 ) << endl;
58 } // end function modifyElement (3 of 3)
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.
49

7.5 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 // Fig. 7.15: fig07_15.cpp
50
2 // Demonstrating the const type qualifier.
Outline
3 #include <iostream> Using const to prevent the
4 using std::cout; function from modifying the array
5 using std::endl;
6 fig07_15.cpp
7 void tryToModifyArray( const int [] ); // function prototype
8 (1 of 2)
9 int main()
Array a will be const when in
10 {
the body of the function
11 int a[] = { 10, 20, 30 };
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
51
20 // to modify the original array "a" in main.
Outline
21 void tryToModifyArray( const int b[] )
22 {
23 b[ 0 ] /= 2; // error
Array cannot be modified; it is
24 b[ 1 ] /= 2; // error fig07_15.cpp
25 b[ 2 ] /= 2; // error
const within the body function
26 } // end function tryToModifyArray (2 of 2)
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.
52
7.6 Case Study: Class GradeBook Using
an Array to Store Grades
• Class GradeBook
– Represent a grade book that stores and analyzes grades
– Can now store grades in an array
• static data members
– Also called class variables
– Variables for which each object of a class does not have a
separate copy
• One copy is shared among all objects of the class
– Can be accessed even when no objects of the class exist
• Use the class name followed by the binary scope resolution
operator and the name of the static data member

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.16: GradeBook.h
53
2
3
// Definition of class GradeBook that uses an array to store test grades.
// Member functions are defined in GradeBook.cpp
Outline
4
5 #include <string> // program uses C++ Standard Library string class
6 using std::string;
fig07_16.cpp
7 students is a static class variable
8 // GradeBook class definition
(1 of 1)
9 class GradeBook Number of students we
10 { will be keeping track of
11 public:
12 // constant -- number of students who took the test
13 const static int students = 10; // note public data
14
15 // constructor initializes course name and array of grades
16 GradeBook( string, const int [] );
17
18 void setCourseName( string ); // function to set the course name
19 string getCourseName(); // function to retrieve the course name
20 void displayMessage(); // display a welcome message
21 void processGrades(); // perform various operations on the grade data
22 int getMinimum(); // find the minimum grade for the test
23 int getMaximum(); // find the maximum grade for the test
24 double getAverage(); // determine the average grade for the test
25 void outputBarChart(); // output bar chart of grade distribution
26 void outputGrades(); // output the contents of the grades array
27 private:
28 string courseName; // course name for this grade book Declare array grades to
29 int grades[ students ]; // array of student grades store individual grades
30 }; // end class GradeBook

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 7.17: GradeBook.cpp
54
2
3
// Member-function definitions for class GradeBook that
// uses an array to store test grades.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::cin;
fig07_17.cpp
7 using std::endl;
8 using std::fixed;
9
(1 of 6)
10 #include <iomanip>
11 using std::setprecision;
12 using std::setw;
13
14 #include "GradeBook.h" // GradeBook class definition
15
16 // constructor initializes courseName and grades array
17 GradeBook::GradeBook( string name, const int gradesArray[] )
18 {
19 setCourseName( name ); // initialize courseName
20
21 // copy grades from gradeArray to grades data member
22 for ( int grade = 0; grade < students; grade++ )
Copy elements from gradesArray
23 grades[ grade ] = gradesArray[ grade ]; to data member grades
24 } // end GradeBook constructor
25
26 // function to set the course name
27 void GradeBook::setCourseName( string name )
28 {
29 courseName = name; // store the course name
30 } // end function setCourseName

 2006 Pearson Education,


Inc. All rights reserved.
31
55
32 // function to retrieve the course name
33 string GradeBook::getCourseName()
Outline
34 {
35 return courseName;
36 } // end function getCourseName
fig07_17.cpp
37
38 // display a welcome message to the GradeBook user
39 void GradeBook::displayMessage()
(2 of 6)
40 {
41 // this statement calls getCourseName to get the
42 // name of the course this GradeBook represents
43 cout << "Welcome to the grade book for\n" << getCourseName() << "!"
44 << endl;
45 } // end function displayMessage
46
47 // perform various operations on the data
48 void GradeBook::processGrades()
49 {
50 // output grades array
51 outputGrades();
52
53 // call function getAverage to calculate the average grade
54 cout << "\nClass average is " << setprecision( 2 ) << fixed <<
55 getAverage() << endl;
56
57 // call functions getMinimum and getMaximum
58 cout << "Lowest grade is " << getMinimum() << "\nHighest grade is "
59 << getMaximum() << endl;

 2006 Pearson Education,


Inc. All rights reserved.
60
56
61
62
// call function outputBarChart to print grade distribution chart
outputBarChart();
Outline
63 } // end function processGrades
64
65 // find minimum grade fig07_17.cpp
66 int GradeBook::getMinimum()
67 {
(3 of 6)
68 int lowGrade = 100; // assume lowest grade is 100
69 Loop through grades
70 // loop through grades array
to find the lowest grade
71 for ( int grade = 0; grade < students; grade++ )
72 {
73 // if current grade lower than lowGrade, assign it to lowGrade
74 if ( grades[ grade ] < lowGrade )
75 lowGrade = grades[ grade ]; // new lowest grade
76 } // end for
77
78 return lowGrade; // return lowest grade
79 } // end function getMinimum
80
81 // find maximum grade

82 int GradeBook::getMaximum()

 2006 Pearson Education,


Inc. All rights reserved.
83 {
57
84
85
int highGrade = 0; // assume highest grade is 0
Outline
Loop through grades to
86 // loop through grades array find the highest grade
87 for ( int grade = 0; grade < students; grade++ )
88 {
fig07_17.cpp
89 // if current grade higher than highGrade, assign it to highGrade
90 if ( grades[ grade ] > highGrade )
91 highGrade = grades[ grade ]; // new highest grade
(4 of 6)
92 } // end for
93
94 return highGrade; // return highest grade
95 } // end function getMaximum
96
97 // determine average grade for test
98 double GradeBook::getAverage()
99 {
100 int total = 0; // initialize total
101
102 // sum grades in array Loop through grades to
103 for ( int grade = 0; grade < students; grade++ ) sum grades for all students
104 total += grades[ grade ];
105
106 // return average of grades
107 return static_cast< double >( total ) / students; Divide the total by the number of
108 } // end function getAverage students to calculate the average grade
109
110 // output bar chart displaying grade distribution
111 void GradeBook::outputBarChart()

 2006 Pearson Education,


Inc. All rights reserved.
112 {
58
113
114
cout << "\nGrade distribution:" << endl;
Outline
115 // stores frequency of grades in each range of 10 grades
116 const int frequencySize = 11;
117 int frequency[ frequencySize ] = { 0 };
fig07_17.cpp
118
119 // for each grade, increment the appropriate frequency
120 for ( int grade = 0; grade < students; grade++ )
(5 of 6)
121 frequency[ grades[ grade ] / 10 ]++;
122
123 // for each grade frequency, print bar in chart
124 for ( int count = 0; count < frequencySize; count++ ) Loop through grades
125 {
to calculate frequency
126 // output bar labels ("0-9:", ..., "90-99:", "100:" )
127 if ( count == 0 )
128 cout << " 0-9: ";
129 else if ( count == 10 )
130 cout << " 100: ";
131 else
132 cout << count * 10 << "-" << ( count * 10 ) + 9 << ": ";
133
134 // print bar of asterisks
135 for ( int stars = 0; stars < frequency[ count ]; stars++ )
136 cout << '*';
137 Display asterisks to show a
138 cout << endl; // start a new line of output bar for each grade range

 2006 Pearson Education,


Inc. All rights reserved.
139 } // end outer for
59
140 } // end function outputBarChart
Outline
141
142 // output the contents of the grades array
143 void GradeBook::outputGrades()
144 { fig07_17.cpp
145 cout << "\nThe grades are:\n\n";
146 (6 of 6)
147 // output each student's grade
148 for ( int student = 0; student < students; student++ )
149 cout << "Student " << setw( 2 ) << student + 1 << ": " << setw( 3 )
150 << grades[ student ] << endl;
151 } // end function outputGrades

Displaying each grade

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 7.18: fig07_18.cpp
60
2 // Creates GradeBook object using an array of grades.
Outline
3
4 #include "GradeBook.h" // GradeBook class definition
5 Use static data member
6 // function main begins program execution students of class GradeBook
fig07_18.cpp
7 int main()
8 { (1 of 2)
9 // array of student grades
10 int gradesArray[ GradeBook::students ] =
11 { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
12
13 GradeBook myGradeBook( Declare and initialize
14 "CS101 Introduction to C++ Programming", gradesArray ); gradesArray with 10 elements
15 myGradeBook.displayMessage();
16 myGradeBook.processGrades();
17 return 0;
18 } // end main Pass gradesArray to GradeBook constructor

 2006 Pearson Education,


Inc. All rights reserved.
Welcome to the grade book for 61
CS101 Introduction to C++ Programming! Outline
The grades are:

Student 1: 87
Student 2: 68 fig07_18.cpp
Student 3: 94
Student 4: 100
Student 5: 83 (2 of 2)
Student 6: 78
Student 7: 85
Student 8: 91
Student 9: 76
Student 10: 87

Class average is 84.90


Lowest grade is 68
Highest grade is 100

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.
62

7.7 Searching Arrays with Linear Search

• Arrays may store large amounts of data


– May need to determine if certain key value is located in an array
• Linear search
– Compares each element of an array with a search key
– Just as likely that the value will be found in the first element as
the last
• On average, program must compare the search key with half the
elements of the array
– To determine that value is not in array, program must compare
the search key to every element in the array
– Works well for small or unsorted arrays

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.19: fig07_19.cpp
63
2
3
// Linear search of an array.
Outline
#include <iostream> Function takes an array, a key value, and
4 using std::cout;
the size of the array as arguments
5 using std::cin;
6 using std::endl;
fig07_19.cpp
7
8 int linearSearch( const int [], int, int ); // prototype
9
(1 of 2)
10 int main()
11 {
12 const int arraySize = 100; // size of array a
13 int a[ arraySize ]; // create array a
14 int searchKey; // value to locate in array a
15
16 for ( int i = 0; i < arraySize; i++ )
17 a[ i ] = 2 * i; // create some data
18
19 cout << "Enter integer search key: ";
20 cin >> searchKey;
21
22 // attempt to locate searchKey in array a
23 int element = linearSearch( a, searchKey, arraySize );
24

Function returns location of


key value, -1 if not found

 2006 Pearson Education,


Inc. All rights reserved.
25 // display results
64
26
27
if ( element != -1 )
cout << "Found value in element " << element << endl;
Outline
28 else
29 cout << "Value not found" << endl;
30 fig07_19.cpp
31 return 0; // indicates successful termination
32 } // end main
(2 of 2)
33
34 // compare key to every element of array until location is
35 // found or until end of array is reached; return subscript of
36 // element if key or -1 if key not found
37 int linearSearch( const int array[], int key, int sizeOfArray )
38 { Search through entire array
39 for ( int j = 0; j < sizeOfArray; j++ )
40 if ( array[ j ] == key ) // if found,
41 return j; // return location of key
42
Return location if current
43 return -1; // key not found
value equals key value
44 } // end function linearSearch

Enter integer search key: 36


Found value in element 18

Enter integer search key: 37


Value not found

 2006 Pearson Education,


Inc. All rights reserved.
65

7.8 Sorting Arrays with Insertion Sort

• Sorting data
– One of the most important computing applications
• Virtually every organization must sort some data
• Insertion sort
– Simple but inefficient
– First iteration takes second element
• If it is less than the first element, swap it with first element
– Second iteration looks at the third element
• Insert it into the correct position with respect to first two
elements
– …
– At the ith iteration of this algorithm, the first i elements in
the original array will be sorted

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.20: fig07_20.cpp
66
2
3
// This program sorts an array's values into ascending order.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig07_20.cpp
7 #include <iomanip>
8 using std::setw;
9
(1 of 2)
10 int main()
11 {
12 const int arraySize = 10; // size of array a
13 int data[ arraySize ] = { 34, 56, 4, 10, 77, 51, 93, 30, 5, 52 };
14 int insert; // temporary variable to hold element to insert
15
16 cout << "Unsorted array:\n";
17
18 // output original array
19 for ( int i = 0; i < arraySize; i++ )
20 cout << setw( 4 ) << data[ i ];
21 For each array element
22 // insertion sort
23 // loop over the elements of the array
24 for ( int next = 1; next < arraySize; next++ )
25 {
26 insert = data[ next ]; // store the value in the current element
27
28 int moveItem = next; // initialize location to place element

 2006 Pearson Education,


Inc. All rights reserved.
29
67
30
31
// search for the location in which to put the current element
while ( ( moveItem > 0 ) && ( data[ moveItem - 1 ] > insert ) )
Outline
32 {
33 // shift element one slot to the right
34 data[ moveItem ] = data[ moveItem - 1 ];
Find location where current
fig07_20.cpp
element should reside
35 moveItem--;
36 } // end while
37
(2 of 2)
38 data[ moveItem ] = insert; // place inserted element into the array
39 } // end for
40
41 cout << "\nSorted array:\n";
42 Place element in proper location
43 // output sorted array
44 for ( int i = 0; i < arraySize; i++ )
45 cout << setw( 4 ) << data[ i ];
46
47 cout << endl;
48 return 0; // indicates successful termination
49 } // end main

Unsorted array:
34 56 4 10 77 51 93 30 5 52
Sorted array:
4 5 10 30 34 51 52 56 77 93

 2006 Pearson Education,


Inc. All rights reserved.
68

7.9 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

7.9 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.


70

Fig.7.21 | Two-dimensional array with three rows and four columns.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.22: fig07_22.cpp
71
2
3
// Initializing multidimensional arrays.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
7 void printArray( const int [][ 3 ] ); // prototype
fig07_22.cpp
8
9 int main() (1 of 2)
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
72
26 // output array with two rows and three columns
27 void printArray( const int a[][ 3 ] )
Outline
28 {
29 // loop through array's rows
30 for ( int i = 0; i < 2; i++ )
fig07_22.cpp
31 {
32 // loop through columns of current row
(2 of 2)
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.
73

7.9 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.


74

7.9 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.


75
7.10 Case Study: Class GradeBook Using
a Two-Dimensional Array
• Class GradeBook
– One-dimensional array
• Store student grades on a single exam
– Two-dimensional array
• Store multiple grades for a single student and multiple
students for the class as a whole
– Each row represents a student’s grades
– Each column represents all the grades the students
earned for one particular exam

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.23: GradeBook.h
76
2 // Definition of class GradeBook that uses a
Outline
3 // two-dimensional array to store test grades.
4 // Member functions are defined in GradeBook.cpp
5 #include <string> // program uses C++ Standard Library string class
6 using std::string; fig07_23.cpp
7
8 // GradeBook class definition (1 of 2)
9 class GradeBook
10 {
11 public:
12 // constants
13 const static int students = 10; // number of students
14 const static int tests = 3; // number of tests
15
16 // constructor initializes course name and array of grades
17 GradeBook( string, const int [][ tests ] );

GradeBook constructor accepts a


string and a two-dimensional array

 2006 Pearson Education,


Inc. All rights reserved.
18
77
19 void setCourseName( string ); // function to set the course name
Outline
20 string getCourseName(); // function to retrieve the course name
21 void displayMessage(); // display a welcome message
22 void processGrades(); // perform various operations on the grade data
23 int getMinimum(); // find the minimum grade in the grade book fig07_23.cpp
24 int getMaximum(); // find the maximum grade in the grade book
25 double getAverage( const int [], const int ); // find average of grades (2 of 2)
26 void outputBarChart(); // output bar chart of grade distribution
27 void outputGrades(); // output the contents of the grades array
28 private:
29 string courseName; // course name for this grade book
30 int grades[ students ][ tests ]; // two-dimensional array of grades
31 }; // end class GradeBook

Declare two-dimensional array grades

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 7.24: GradeBook.cpp
78
2
3
// Member-function definitions for class GradeBook that
// uses a two-dimensional array to store grades.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::cin;
fig07_24.cpp
7 using std::endl;
8 using std::fixed;
9
(1 of 7)
10 #include <iomanip> // parameterized stream manipulators
11 using std::setprecision; // sets numeric output precision
12 using std::setw; // sets field width
13
14 // include definition of class GradeBook from GradeBook.h
15 #include "GradeBook.h"
16
17 // two-argument constructor initializes courseName and grades array
18 GradeBook::GradeBook( string name, const int gradesArray[][ tests ] )
19 {
20 setCourseName( name ); // initialize courseName Use nested for loops to copy elements
21 from gradesArray to grades
22 // copy grades from gradeArray to grades
23 for ( int student = 0; student < students; student++ )
24
25 for ( int test = 0; test < tests; test++ )
26 grades[ student ][ test ] = gradesArray[ student ][ test ];
27 } // end two-argument GradeBook constructor
28

 2006 Pearson Education,


Inc. All rights reserved.
29 // function to set the course name
79
30 void GradeBook::setCourseName( string name )
31 {
Outline
32 courseName = name; // store the course name
33 } // end function setCourseName
34
fig07_24.cpp
35 // function to retrieve the course name
36 string GradeBook::getCourseName()
37 {
(2 of 7)
38 return courseName;
39 } // end function getCourseName
40
41 // display a welcome message to the GradeBook user
42 void GradeBook::displayMessage()
43 {
44 // this statement calls getCourseName to get the
45 // name of the course this GradeBook represents
46 cout << "Welcome to the grade book for\n" << getCourseName() << "!"
47 << endl;
48 } // end function displayMessage
49
50 // perform various operations on the data
51 void GradeBook::processGrades()
52 {
53 // output grades array
54 outputGrades();
55
56 // call functions getMinimum and getMaximum
57 cout << "\nLowest grade in the grade book is " << getMinimum()
58 << "\nHighest grade in the grade book is " << getMaximum() << endl;

 2006 Pearson Education,


Inc. All rights reserved.
59
80
60
61
// output grade distribution chart of all grades on all tests
outputBarChart();
Outline
62 } // end function processGrades
63
64 // find minimum grade
fig07_24.cpp
65 int GradeBook::getMinimum()
66 {
67 int lowGrade = 100; // assume lowest grade is 100
(3 of 7)
68
69 // loop through rows of grades array
70 for ( int student = 0; student < students; student++ )
71 {
72 // loop through columns of current row
73 for ( int test = 0; test < tests; test++ )
74 {
75 // if current grade less than lowGrade, assign it to lowGrade
76 if ( grades[ student ][ test ] < lowGrade )
77 lowGrade = grades[ student ][ test ]; // new lowest grade
78 } // end inner for
79 } // end outer for
80
Loop through rows and columns of grades
81 return lowGrade; // return lowest grade to find the lowest grade of any student
82 } // end function getMinimum
83

 2006 Pearson Education,


Inc. All rights reserved.
84 // find maximum grade 81
85 int GradeBook::getMaximum() Outline
86 {
87 int highGrade = 0; // assume highest grade is 0
88
89 // loop through rows of grades array fig07_24.cpp
90 for ( int student = 0; student < students; student++ )
91 { (4 of 7)
92 // loop through columns of current row
93 for ( int test = 0; test < tests; test++ )
94 {
95 // if current grade greater than lowGrade, assign it to highGrade
96 if ( grades[ student ][ test ] > highGrade )
97 highGrade = grades[ student ][ test ]; // new highest grade
98 } // end inner for
99 } // end outer for
100 Loop through rows and columns of grades
101 return highGrade; // return highest grade to find the highest grade of any student
102 } // end function getMaximum
103
104 // determine average grade for particular set of grades
105 double GradeBook::getAverage( const int setOfGrades[], const int grades )
106 {
107 int total = 0; // initialize total
108
109 // sum grades in array
110 for ( int grade = 0; grade < grades; grade++ )
111 total += setOfGrades[ grade ];
112
 2006 Pearson Education,
Inc. All rights reserved.
113 // return average of grades
82
114 return static_cast< double >( total ) / grades;
115 } // end function getAverage
Outline
116
117 // output bar chart displaying grade distribution
118 void GradeBook::outputBarChart()
fig07_24.cpp
119 {
120 cout << "\nOverall grade distribution:" << endl;
121
(5 of 7)
122 // stores frequency of grades in each range of 10 grades
123 const int frequencySize = 11;
124 int frequency[ frequencySize ] = { 0 };
125
126 // for each grade, increment the appropriate frequency
127 for ( int student = 0; student < students; student++ )
128
129 for ( int test = 0; test < tests; test++ )
130 ++frequency[ grades[ student ][ test ] / 10 ];
131
132 // for each grade frequency, print bar in chart
Calculate the distribution
133 for ( int count = 0; count < frequencySize; count++ )
of all student grades
134 {
135 // output bar label ("0-9:", ..., "90-99:", "100:" )
136 if ( count == 0 )
137 cout << " 0-9: ";
138 else if ( count == 10 )
139 cout << " 100: ";
140 else
141 cout << count * 10 << "-" << ( count * 10 ) + 9 << ": ";
142
 2006 Pearson Education,
Inc. All rights reserved.
143 // print bar of asterisks
83
144 for ( int stars = 0; stars < frequency[ count ]; stars++ )
Outline
145 cout << '*';
146
147 cout << endl; // start a new line of output
148 } // end outer for fig07_24.cpp
149 } // end function outputBarChart
150 (6 of 7)
151 // output the contents of the grades array
152 void GradeBook::outputGrades()
153 {
154 cout << "\nThe grades are:\n\n";
155 cout << " "; // align column heads
156
157 // create a column heading for each of the tests
158 for ( int test = 0; test < tests; test++ )
159 cout << "Test " << test + 1 << " ";
160
161 cout << "Average" << endl; // student average column heading
162
163 // create rows/columns of text representing array grades
164 for ( int student = 0; student < students; student++ )
165 {
166 cout << "Student " << setw( 2 ) << student + 1;
167

 2006 Pearson Education,


Inc. All rights reserved.
168 // output student's grades
84
169
170
for ( int test = 0; test < tests; test++ )
cout << setw( 8 ) << grades[ student ][ test ];
Outline
171
172 // call member function getAverage to calculate student's average;
173 // pass row of grades and the value of tests as the arguments
fig07_24.cpp
174 double average = getAverage( grades[ student ], tests );
175 cout << setw( 9 ) << setprecision( 2 ) << fixed << average << endl;
176 } // end outer for
(7 of 7)
177 } // end function outputGrades

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 7.25: fig07_25.cpp
85
2
3
// Creates GradeBook object using a two-dimensional array of grades.
Outline
4 #include "GradeBook.h" // GradeBook class definition
Declare gradesArray
5
6 // function main begins program execution
as 3-by-10 array
fig07_25.cpp
7 int main()
8 {
9 // two-dimensional array of student grades
(1 of 2)
10 int gradesArray[ GradeBook::students ][ GradeBook::tests ] =
11 { { 87, 96, 70 },
12 { 68, 87, 90 },
13 { 94, 100, 90 },
14 { 100, 81, 82 },
15 { 83, 65, 85 },
16 { 78, 87, 65 },
17 { 85, 75, 83 },
18 { 91, 94, 100 },
19 { 76, 72, 84 },
Each row represents a student; each
20 { 87, 93, 73 } };
column represents an exam grade
21
22 GradeBook myGradeBook(
23 "CS101 Introduction to C++ Programming", gradesArray );
24 myGradeBook.displayMessage();
25 myGradeBook.processGrades();
26 return 0; // indicates successful termination
27 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
Welcome to the grade book for 86
CS101 Introduction to C++ Programming! Outline
The grades are:

Test 1 Test 2 Test 3 Average


Student 1 87 96 70 84.33
Student 2 68 87 90 81.67 fig07_25.cpp
Student 3 94 100 90 94.67
Student 4 100 81 82 87.67
Student 5 83 65 85 77.67 (2 of 2)
Student 6 78 87 65 76.67
Student 7 85 75 83 81.00
Student 8 91 94 100 95.00
Student 9 76 72 84 77.33
Student 10 87 93 73 84.33

Lowest grade in the grade book is 65


Highest grade in the grade book is 100

Overall 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.
87
7.11 Introduction to C++ Standard Library
Class Template vector
• C-style pointer-based arrays
– Have great potential for errors and several shortcomings
• C++ does not check whether subscripts fall outside the range
of the array
• Two arrays cannot be meaningfully compared with equality
or relational operators
• One array cannot be assigned to another using the
assignment operators

 2006 Pearson Education, Inc. All rights reserved.


88
7.11 Introduction to C++ Standard Library
Class Template vector (Cont.)
• Class template vector
– Available to anyone building applications with C++
– Can be defined to store any data type
• Specified between angle brackets in vector< type >
• All elements in a vector are set to 0 by default
– Member function size obtains size of array
• Number of elements as a value of type size_t
– vector objects can be compared using equality and
relational operators
– Assignment operator can be used for assigning vectors

 2006 Pearson Education, Inc. All rights reserved.


89
7.11 Introduction to C++ Standard Library
Class Template vector (Cont.)
• vector elements can be obtained as an
unmodifiable lvalue or as a modifiable lvalue
– Unmodifiable lvalue
• Expression that identifies an object in memory, but cannot be
used to modify that object
– Modifiable lvalue
• Expression that identifies an object in memory, can be used
to modify the object

 2006 Pearson Education, Inc. All rights reserved.


90
7.11 Introduction to C++ Standard Library
Class Template vector (Cont.)
• vector member function at
– Provides access to individual elements
– Performs bounds checking
• Throws an exception when specified index is invalid
• Accessing with square brackets does not perform bounds
checking

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 7.26: fig07_26.cpp
91
2
3
// Demonstrating C++ Standard Library class template vector.
#include <iostream>
Outline
4 using std::cout;
5 using std::cin;
6 using std::endl;
fig07_26.cpp
7 Using const prevents outputVector
8 #include <iomanip> from modifying the vector passed to it(1 of 6)
9 using std::setw;
10
11 #include <vector>
12 using std::vector;
13
14 void outputVector( const vector< int > & ); // display the vector
15 void inputVector( vector< int > & ); // input values into the vector
16
17 int main() These vectors will store ints
18 {
19 vector< int > integers1( 7 ); // 7-element vector< int >
20 vector< int > integers2( 10 ); // 10-element vector< int >
21
22 // print integers1 size and contents
23 cout << "Size of vector integers1 is " << integers1.size()
24 << "\nvector after initialization:" << endl;
25 outputVector( integers1 ); Function size returns number
26 of elements in the vector
27 // print integers2 size and contents
28 cout << "\nSize of vector integers2 is " << integers2.size()
29 << "\nvector after initialization:" << endl;
30 outputVector( integers2 );

 2006 Pearson Education,


Inc. All rights reserved.
31
92
32
33
// input and print integers1 and integers2
cout << "\nEnter 17 integers:" << endl;
Outline
34 inputVector( integers1 );
35 inputVector( integers2 );
36
fig07_26.cpp
37 cout << "\nAfter input, the vectors contain:\n"
38 << "integers1:" << endl;
39 outputVector( integers1 );
(2 of 6)
40 cout << "integers2:" << endl;
41 outputVector( integers2 );
42
43 // use inequality (!=) operator with vector objects
44 cout << "\nEvaluating: integers1 != integers2" << endl;
45
Comparing vectors using !=
46 if ( integers1 != integers2 )
47 cout << "integers1 and integers2 are not equal" << endl;
48
Copying data from one
49 // create vector integers3 using integers1 as an
50 // initializer; print size and contents
vector to another
51 vector< int > integers3( integers1 ); // copy constructor
52
53 cout << "\nSize of vector integers3 is " << integers3.size()
54 << "\nvector after initialization:" << endl;
55 outputVector( integers3 );
56
57 // use overloaded assignment (=) operator
58 cout << "\nAssigning integers2 to integers1:" << endl;
59 integers1 = integers2; // integers1 is larger than integers2

Assigning data from one  2006 Pearson Education,


vector to another Inc. All rights reserved.
60
93
61
62
cout << "integers1:" << endl;
outputVector( integers1 );
Outline
63 cout << "integers2:" << endl;
64 outputVector( integers2 );
65
fig07_26.cpp
66 // use equality (==) operator with vector objects
67 cout << "\nEvaluating: integers1 == integers2" << endl;
68
(3 of 6)
69 if ( integers1 == integers2 ) Comparing vectors using ==
70 cout << "integers1 and integers2 are equal" << endl;
71
72 // use square brackets to create rvalue
73 cout << "\nintegers1[5] is " << integers1[ 5 ]; Displaying a value in the vector
74
75 // use square brackets to create lvalue
76 cout << "\n\nAssigning 1000 to integers1[5]" << endl;
77 integers1[ 5 ] = 1000; Updating a value in the vector
78 cout << "integers1:" << endl;
79 outputVector( integers1 );
80
81 // attempt to use out-of-range subscript
82 cout << "\nAttempt to assign 1000 to integers1.at( 15 )" << endl;
83 integers1.at( 15 ) = 1000; // ERROR: out of range
84 return 0;
85 } // end main

Function at provides bounds checking

 2006 Pearson Education,


Inc. All rights reserved.
86
94
87 // output vector contents
88 void outputVector( const vector< int > &array )
Outline
89 {
90 size_t i; // declare control variable
91
92 for ( i = 0; i < array.size(); i++ )
fig07_26.cpp
93 {
94 cout << setw( 12 ) << array[ i ]; (4 of 6)
95
96 if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output Display each vector element
97 cout << endl;
98 } // end for
99
100 if ( i % 4 != 0 )
101 cout << endl;
102 } // end function outputVector
103
104 // input vector contents
105 void inputVector( vector< int > &array )
106 {
107 for ( size_t i = 0; i < array.size(); i++ )
108 cin >> array[ i ];
109 } // end function inputVector
Input vector values using cin

 2006 Pearson Education,


Inc. All rights reserved.
95
Size of vector integers1 is 7
vector after initialization: Outline
0 0 0 0
0 0 0

Size of vector integers2 is 10


vector after initialization: fig07_26.cpp
0 0 0 0
0 0 0 0
0 0 (5 of 6)
Enter 17 integers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

After input, the vectors contain:


integers1:
1 2 3 4
5 6 7
integers2:
8 9 10 11
12 13 14 15
16 17

Evaluating: integers1 != integers2


integers1 and integers2 are not equal

Size of vector integers3 is 7


vector after initialization:
1 2 3 4
5 6 7

(continued at top of next slide )

 2006 Pearson Education,


Inc. All rights reserved.
( continued from bottom of previous slide)
96
Assigning integers2 to integers1: Outline
integers1:
8 9 10 11
12 13 14 15
16 17
integers2: fig07_26.cpp
8 9 10 11
12 13 14 15
16 17 (6 of 6)
Evaluating: integers1 == integers2
integers1 and integers2 are equal

integers1[5] is 13

Assigning 1000 to integers1[5]


integers1:
8 9 10 11
12 1000 14 15
16 17

Attempt to assign 1000 to integers1.at( 15 )

abnormal program termination


Call to function at with an invalid
subscript terminates the program

 2006 Pearson Education,


Inc. All rights reserved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy