Chapter 8
Arrays and Strings
C++ Programming: Program Design Including Data Structures, Eighth Edition
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain
1
product or service or otherwise on a password-protected website for classroom
Objectives (1 of 3)
• In this chapter, you will:
• Learn the reasons for arrays
• Explore how to declare and manipulate data into arrays
• Understand the meaning of ‘‘array index out of bounds’’
• Learn how to declare and initialize arrays
• Become familiar with the restrictions on array processing
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 2
product or service or otherwise on a password-protected website for classroom use.
Objectives (2 of 3)
• Discover how to pass an array as a parameter to a function
• Learn how to search an array
• Learn how to sort an array
• Become aware of auto declarations
• Learn about range-based for loops
• Learn about C-strings
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 3
product or service or otherwise on a password-protected website for classroom use.
Objectives (3 of 3)
• Examine the use of string functions to process C-strings
• Discover how to input data into—and output data from—a C-string
• Learn about parallel arrays
• Discover how to manipulate data in a two-dimensional array
• Learn about multidimensional arrays
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 4
product or service or otherwise on a password-protected website for classroom use.
Introduction
• Simple data type: variables of these types can store only one value at a time
• Structured data type: a data type in which each data item is a collection of
other data items
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 5
product or service or otherwise on a password-protected website for classroom use.
Arrays
• Array: a collection of a fixed number of components, all of the same data type
• One-dimensional array: components are arranged in a list form
• Syntax for declaring a one-dimensional array
• intExp: any constant expression that evaluates to a positive integer
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 6
product or service or otherwise on a password-protected website for classroom use.
Accessing Array Components (1 of 3)
• General syntax
• indexExp: called the index
• An expression with a nonnegative integer value
• Value of the index is the position of the item in the array
• []: array subscripting operator
• Array index always starts at 0
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 7
product or service or otherwise on a password-protected website for classroom use.
Accessing Array Components (2 of 3)
This statement declares an array of 10 components:
int list[10];
FIGURE 8-3 Array list
list[5] = 34;
stores 34 in list[5], the sixth component of the array list
FIGURE 8-4 Array list after execution of the statement list[5]= 34;
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 8
product or service or otherwise on a password-protected website for classroom use.
Accessing Array Components (3 of 3)
list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];
FIGURE 8-5 Array list after execution of the statements list[3]= 10;, list[6]=
35;, and list[5] = list[3] + list[6];
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 9
product or service or otherwise on a password-protected website for classroom use.
Processing One-Dimensional Arrays (1 of 3)
• Basic operations on a one-dimensional array include:
• Initializing
• Inputting data
• Outputting data stored in an array
• Finding the largest and/or smallest element
• Each operation requires ability to step through elements of the array
• Easily accomplished using a loop
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 10
product or service or otherwise on a password-protected website for classroom use.
Processing One-Dimensional Arrays (2 of 3)
• Given the declaration:
• Use a for loop to access array elements:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 11
product or service or otherwise on a password-protected website for classroom use.
Processing One-Dimensional Arrays (3 of 3)
• Refer to Example 8-3 in the text, which shows how loops are used to process
arrays
• Initializing an array
• Reading data into an array
• Printing an array
• Finding the sum and average of an array
• Finding the largest element in an array
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 12
product or service or otherwise on a password-protected website for classroom use.
Array Index Out of Bounds
• The index of an array is in bounds if the index is between 0 and ARRAY_SIZE
- 1
• Otherwise, the index is out of bounds
• In C++, there is no guard against indices that are out of bounds
• This check is solely the programmer’s responsibility
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 13
product or service or otherwise on a password-protected website for classroom use.
Array Initialization During Declaration
• Arrays can be initialized during declaration
– Values are placed between curly braces
• Example 1
double sales[5] = {12.25, 32.50, 16.90, 23, 45.68}
• Example 2: the array size is determined by the number of initial values in the
braces if the array is declared without size specified
double sales[] = {12.25, 32.50, 16.90, 23, 45.68}
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 14
product or service or otherwise on a password-protected website for classroom use.
Partial Initialization of Arrays During Declaration
• The statement:
int list[10] = {0};
– Declares an array of 10 components and initializes all of them to zero
• The statement (an example of partial initialization of an array during
declaration):
int list[10] = {8, 5, 12};
– Declares an array of 10 components and initializes list[0] to 8, list[1] to 5,
list[2] to 12
– All other components are initialized to 0
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 15
product or service or otherwise on a password-protected website for classroom use.
Some Restrictions on Array Processing
• Aggregate operation: any operation that manipulates the entire array as a
single unit
• Not allowed on arrays in C++
• Example
• Solution
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 16
product or service or otherwise on a password-protected website for classroom use.
Arrays as Parameters to Functions
• Arrays are passed by reference only
• Do not use symbol & when declaring an array as a formal parameter
• The size of the array is usually omitted in the array parameter
• If provided, it is ignored by the compiler
• The following example illustrates a function header, which includes an array
parameter and a parameter specifying the number of elements in the array:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 17
product or service or otherwise on a password-protected website for classroom use.
Constant Arrays as Formal Parameters
• Can prevent a function from changing the actual parameter when passed by
reference
• Use const in the declaration of the formal parameter
• Example
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 18
product or service or otherwise on a password-protected website for classroom use.
Base Address of an Array and Array in Computer Memory
• The base address of an array is the address (memory location) of the first array
component
• If list is a one-dimensional array, its base address is the address of list[0]
• When an array is passed as a parameter, the base address of the actual array is
passed to the formal parameter
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 19
product or service or otherwise on a password-protected website for classroom use.
Functions Cannot Return a Value of the Type Array
• C++ does not allow functions to return a value of type array
• Refer to Example 8-6 in the text
• Functions sumArray and indexLargestElement
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 20
product or service or otherwise on a password-protected website for classroom use.
Integral Data Type and Array Indices
• C++ allows any integral type to be used as an array index
• Improves code readability
• The following code illustrates improved readability:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 21
product or service or otherwise on a password-protected website for classroom use.
Other Ways to Declare Arrays
• Example 1
• Example 2
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 22
product or service or otherwise on a password-protected website for classroom use.
Searching an Array for a Specific Item
• Sequential search (or linear search)
• Searching a list for a given item, starting from the first array element
• Compare each element in the array with value that is being searched
• Continue the search until item is found or no more data is left in the list
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 23
product or service or otherwise on a password-protected website for classroom use.
Sorting
• Selection sort: rearrange the list by selecting an element and moving it to its
proper position
• Steps for a selection sort:
• Find the smallest element in the unsorted portion of the list
• Move it to the top of the unsorted portion by swapping with the element currently
there
• Start again with the rest of the list
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 24
product or service or otherwise on a password-protected website for classroom use.
Selection Sort
FIGURE 8-10 Elements of list during the first iteration
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 25
product or service or otherwise on a password-protected website for classroom use.
Auto Declaration and Range-Based for Loops
• C++11 allows auto declaration of variables
– Data type does not need to be specified
auto num = 15;
The type of num will be int
• Range-based for loop
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 26
product or service or otherwise on a password-protected website for classroom use.
C-Strings (Character Arrays) (1 of 3)
• A character array is an array whose components are of type char
• C-strings are null-terminated ('\0') character arrays
• Examples
• 'A' is the character A
• "A" is the C-string A
• Note: "A" represents two characters, 'A' and '\0'
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 27
product or service or otherwise on a password-protected website for classroom use.
C-Strings (Character Arrays) (2 of 3)
• This is an example of a C-string declaration:
char name[16];
• Since C-strings are null terminated and name has 16 components, the largest
string it can store has 15 characters
• If you store a string whose length is less than the array size, the last
components are unused
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 28
product or service or otherwise on a password-protected website for classroom use.
C-Strings (Character Arrays) (3 of 3)
• The size of an array can be omitted if the array is initialized during declaration
– Declares an array of length 5 and stores the C-string "John" in the array
• Useful string manipulation functions include:
– strcpy
– strncpy
– strcmp
– strlen
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 29
product or service or otherwise on a password-protected website for classroom use.
String Comparison
• C-strings are compared character by character using the collating sequence of
the system
• Use the function strcmp
• If using the ASCII character set:
• "Air" < "Boat"
• "Air" < "An"
• "Bill" < "Billy"
• "Hello" < "hello"
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 30
product or service or otherwise on a password-protected website for classroom use.
Reading and Writing Strings
• Most rules for arrays also apply to C-strings (which are character arrays)
• Aggregate operations, such as assignment and comparison, are not allowed on
arrays
• C++ does allow aggregate operations for the input and output of C-strings
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 31
product or service or otherwise on a password-protected website for classroom use.
String Input
• This is an example of string input:
• Stores the next input C-string into name
• To read strings with blanks, use the function get:
• When executed , the statement stores the next m characters into str, but the newline
character is not stored in str
• If input string has fewer than m characters, reading stops at the newline character
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 32
product or service or otherwise on a password-protected website for classroom use.
String Output
• Example
• Outputs the content of name on the screen
• continues to write the contents of name until it finds the null character
• If name does not contain the null character, then strange output may occur since
continues to output data from memory adjacent to name until a '\0' is found
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 33
product or service or otherwise on a password-protected website for classroom use.
Specifying Input/Output Files at Execution Time
• User can specify the name of an input and/or output file at execution time
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 34
product or service or otherwise on a password-protected website for classroom use.
string Type and Input/Output Files
• Argument to the open function must be a null-terminated string (a C-string)
• If using a string variable for the name of an I/O file, the value must first be
converted to a C-string before calling open
- Use the c_str function to convert
• The syntax to use the function c_str is:
• Where strVar is a variable of type string
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 35
product or service or otherwise on a password-protected website for classroom use.
Parallel Arrays
• Two (or more) arrays are called parallel if their corresponding components hold related
information
• The following example illustrates two parallel arrays:
int studentId[50];
char courseGrade[50];
With the following sample data to enter into the arrays:
studentId courseGrade
23456 A
86723 B
22356 C
92733 B
11892 D
.
.
.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 36
product or service or otherwise on a password-protected website for classroom use.
Two- and Multidimensional Arrays
• Two-dimensional array: a collection of a fixed number of components (of the
same type) arranged in two dimensions
– Sometimes called matrices or tables
• Declaration syntax
• intExp1 and intExp2 are expressions with positive integer values specifying the
number of rows and columns in the array
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 37
product or service or otherwise on a password-protected website for classroom use.
Accessing Array Components (1 of 2)
• Syntax to access a component in a two-dimensional array
• Where indexExp1 and indexExp2 are expressions with positive integer values,
and specify the row and column position
• Example: sales[5][3] = 25.75;
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 38
product or service or otherwise on a password-protected website for classroom use.
Accessing Array Components (2 of 2)
FIGURE 8-14 sales[5][3]
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 39
product or service or otherwise on a password-protected website for classroom use.
Two-Dimensional Array Initialization During Declaration
• Two-dimensional arrays can be initialized when they are declared
• Elements of each row are enclosed within braces and separated by commas
• All rows are enclosed within braces
• For number arrays, unspecified elements are set to 0
• An example of two-dimensional array initialization is shown below:
int board[4][3] = {{2, 3, 1},
{15, 25, 13},
{20, 4, 7},
{11, 18, 14}};
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 40
product or service or otherwise on a password-protected website for classroom use.
Two-Dimensional Arrays and Enumeration Types
• Enumeration types can be used for array indices
const int NUMBER_OF_ROWS = 6;
const int NUMBER_OF_COLUMNS = 5;
enum carType {GM, FORD, TOYOTA, BMW, NISSAN, VOLVO};
enum colorType {RED, BROWN, BLACK, WHITE, GRAY};
int inStock[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 41
product or service or otherwise on a password-protected website for classroom use.
Processing Two-Dimensional Arrays
• Ways to process a two-dimensional array:
• Process a single element
• Process the entire array
• Process a single row at a time, called row processing
• Process a single column at a time, called column processing
• Each row and each column of a two-dimensional array is a one-dimensional
array
• To process, use algorithms similar to processing one-dimensional arrays
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 42
product or service or otherwise on a password-protected website for classroom use.
Initialization
• An example initializing row number 4 (fifth row) to 0:
• An example initializing the entire matrix to 0
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 43
product or service or otherwise on a password-protected website for classroom use.
Print
• Use a nested loop to output the components of a two dimensional array
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 44
product or service or otherwise on a password-protected website for classroom use.
Input
• An example of adding input to row number 4 (fifth row):
• An example of adding input to each component of matrix:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 45
product or service or otherwise on a password-protected website for classroom use.
Sum by Row
• The following example shows how to find the sum of row number 4:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 46
product or service or otherwise on a password-protected website for classroom use.
Sum by Column
• The following example illustrates finding the sum of each individual column:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 47
product or service or otherwise on a password-protected website for classroom use.
Largest Element in Each Row and Each Column
• The following example finds the largest element in each row:
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 48
product or service or otherwise on a password-protected website for classroom use.
Passing Two-Dimensional Arrays as Parameters to Functions
• Two-dimensional arrays are passed by reference as parameters to a function
• The base address is passed to the formal parameter
• Two-dimensional arrays are stored in row order form
• When declaring a two-dimensional array as a formal parameter, you can omit
the size of the first dimension, but not the second
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 49
product or service or otherwise on a password-protected website for classroom use.
Arrays of Strings
• Strings in C++ can be manipulated using either the data type string or
character arrays (C-strings)
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 50
product or service or otherwise on a password-protected website for classroom use.
Arrays of Strings and the string Type
• The example below declares an array of 100 components of type string:
string list[100];
• Basic operations, such as assignment, comparison, and input/output, can be
performed on values of the string type
• The data in list can be processed just like any one-dimensional array
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 51
product or service or otherwise on a password-protected website for classroom use.
Arrays of Strings and C-Strings (Character Arrays)
strcpy(list[1], "Snow White");
FIGURE 8-20 Array list, showing list[1]
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 52
product or service or otherwise on a password-protected website for classroom use.
Another Way to Declare a Two-Dimensional Array
• Can use typedef to define a two-dimensional array data type:
const int NUMBER_OF_ROWS = 20;
const int NUMBER_OF_COLUMNS = 10;
typedef int tableType[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
• This statement declares an array of 20 rows and 10 columns:
tableType matrix;
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 53
product or service or otherwise on a password-protected website for classroom use.
Multidimensional Arrays
• n-dimensional array: a collection of a fixed number of elements arranged in n
dimensions (n >= 1)
• Declaration syntax
• Code to access a component
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 54
product or service or otherwise on a password-protected website for classroom use.
Quick Review (1 of 4)
• An array is a structured data type with a fixed number of components of the
same type
• Components are accessed using their relative positions in the array
• Elements of a one-dimensional array are arranged in the form of a list
• An array index can be any expression that evaluates to a nonnegative integer
• Must always be less than the size of the array
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 55
product or service or otherwise on a password-protected website for classroom use.
Quick Review (2 of 4)
• The base address of an array is the address of the first array component
• When passing an array as an actual parameter, use only its name
• Passed by reference only
• A function cannot return an array type value
• Individual array components can be passed as parameters to functions
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 56
product or service or otherwise on a password-protected website for classroom use.
Quick Review (3 of 4)
• In C++, C-strings are null terminated and are stored in character arrays
• Commonly used C-string manipulation functions include: strcpy, strncpy,
strcmp, strncmp, and strlen
• Parallel arrays hold related information
• In a two-dimensional array, the elements are arranged in a table form
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 57
product or service or otherwise on a password-protected website for classroom use.
Quick Review (4 of 4)
• To access an element of a two-dimensional array, you need a pair of indices:
one for row position, one for column position
• In row processing, a two-dimensional array is processed one row at a time
• In column processing, a two-dimensional array is processed one column at a
time
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain 58
product or service or otherwise on a password-protected website for classroom use.