Chapter 8 - Arrays - PPT Slides
Chapter 8 - Arrays - PPT Slides
Arrays
1
Objectives (1 of 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 product or service 2
or otherwise on a password-protected website for classroom
Objectives (2 of 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 product or service 3
or otherwise on a password-protected website for classroom
Objectives (3 of 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 product or service 4
or otherwise on a password-protected website for classroom
Introduction (1 of 3)
• 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 actually collection
of many data items. Simple data types are building blocks of structured data
types.
• Arrays
• Structures
© 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 product or service 5
or otherwise on a password-protected website for classroom
Introduction (2 of 3)
//Program to find the average test score and output the average test score
//and all the test scores that are less than the average test score.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int test0, test1, test2, test3, test4;
double average;
cout << fixed << showpoint << setprecision(2);
cout << "Enter five test scores: ";
cin >> test0 >> test1 >> test2 >> test3 >> test4;
cout << endl;
average = (test0 + test1 + test2 + test3 + test4) / 5.0;
cout << "The average test score = " << average << endl;
if (test0 < average)
cout << test0 << " is less than the average “ << "test score." << endl;
if (test1 < average)
cout << test1 << " is less than the average “ << "test score." << endl;
if (test2 < average)
cout << test2 << " is less than the average “ << "test score." << endl;
if (test3 < average)
cout << test3 << " is less than the average “ << "test score." << endl;
if (test4 < average)
cout << test4 << " is less than the average “ << "test score." << endl;
return 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 product or service 6
or otherwise on a password-protected website for classroom
Introduction (3 of 3)
• For large amounts of data, the previous program is not efficient. Note the following in
the previous program:
1. Five variables must be declared because test scores less than the average test scores need to be
printed.
3. The way in which these variables are declared indicates that the variables to store these
numbers all have the same name—except the last character, which is a number.
4. All the if statements are similar, except the name of the variables to store the test scores.
• The data structure that lets you do handle all of these things efficiently in C++ is called
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 product or service 7
or otherwise on a password-protected website for classroom
Arrays (1 of 2)
• Array: is a collection of a fixed number of components (also called elements) all of the
same data type and in contiguous (that is, adjacent) memory space
• An array is a series of variables of the same type, referenced by the same name, each
one has an index number inside brackets (also called subscript) that differentiates each
variable. Individual element of an are also considered as scalar values and ensemble
they are considered as equivalent to a vector
• Examples: average marks of the students of a class, the list of capitals of the European
countries
• One-dimensional array: components are arranged in a list form
- Syntax for declaring a one-dimensional array
dataType arrayName[intExp];
- 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 product or service 8
or otherwise on a password-protected website for classroom
Arrays (2 of 2)
• The statement:
int num[5];
© 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 product or service 9
or otherwise on a password-protected website for classroom
Accessing Array Components (1 of 4)
FIGURE 8-4 Array list after execution of the statement list[5] = 34;
int i = 1;
list[2*i + 1] = 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 product or service 11
or otherwise on a password-protected website for classroom
Accessing Array Components (3 of 4)
By simply changing the value of ARRAY_SIZE, from program to program, you may
change the number of elements that can be stored in the array 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 product or service 12
or otherwise on a password-protected website for classroom
Accessing Array Components (4 of 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 product or service 13
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (1 of 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 product or service 14
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (2 of 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 product or service 15
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (3 of 6)
a. Initializing an array: The following loop initializes every component of the array sales to 0.0.
for (int index = 0; index < 10; index++)
sales[index] = 0.0;
b. Inputting data into an array: The following loop inputs the data into the array sales. For
simplicity, we assume that the data is entered from the keyboard.
for (int index = 0; index < 10; index++)
cin >> sales[index];
c. Outputting/Printing data from an array: The following loop outputs the array sales. For
simplicity, we assume that the output goes to the screen.
for (int index = 0; index < 10; index++)
cout << sales[index] << " ";
© 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 product or service 16
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (4 of 6)
d. Finding the sum and average of elements of an array: The following C++ code finds the sum of
the elements of the array sales and the average sale amount:
sum = 0;
for (int index = 0; index < 10; index++)
{
sum = sum + sales[index];
}
average = sum / 10;
© 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 product or service 17
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (5 of 6)
Let us demonstrate how this algorithm works with an example. Suppose the array
sales is as given in the following Figure 8-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 product or service 18
or otherwise on a password-protected website for classroom
Processing One-Dimensional Arrays (6 of 6)
//Program to find the average test score and output the average test score
//and all the test scores that are less than the average test score.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int item[5];
int sum = 0;
double average ;
int index ;
cout << fixed << showpoint << setprecision(2);
cout << "Enter five test scores: ";
for (index = 0; index < 5; index++)
{
cin >> test[index];
sum = sum + test[index];
}
cout << endl;
average = sum / 5.0;
cout << "The average test score = " << average << endl;
for (index = 0; index < 5; index++)
if (test[index] < average)
cout << test[index] << " is less than the average “ << "test score." << endl;
return 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 product or service 19
or otherwise on a password-protected website for classroom
Array Index Out of Bounds (1 of 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 product or service 20
or otherwise on a password-protected website for classroom
Array Index Out of Bounds (2 of 2)
• A loop such as the following can set the index out of bounds:
int list[10];
for (i = 0; i <= 10; i++)
list[i] = 0;
When i becomes 10, the loop test condition i <= 10 evaluates to true and the body of the
loop executes, which results in storing 0 in list[10]. Logically, list[10] does not exist.
• If an array index becomes out of bound, the situation can result in altering or accessing
the data of a memory location that you never intended to modify or access, or in trying to
access protected memory that causes the program to instantly halt.
© 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 product or service 21
or otherwise on a password-protected website for classroom
Array Initialization During Declaration
Example 2:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68}
- Although it is not necessary to specify the size of the array if it is initialized during
declaration, it is a good practice to do so.
• The statement:
int list[10] = {0};
Declares an array of 10 components and initializes all of them to zero.
© 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 product or service 22
or otherwise on a password-protected website for classroom
Partial Initialization of Arrays During Declaration
• The statement
int list[10] = {8, 5, 12};
• Note that, here, the size of the array in the declaration statement does matter. For example, the
following statement can not be used for partial initialization:
int list[] = {5, 6, 3}; //Fixed sized array of size 3, all initialized
• When you partially initialize an array, then all of the elements that follow the first uninitialized
element must be uninitialized. Therefore, the following statement will result in a syntax error:
int list[10] = {2, 5, 6, , 8}; //illegal
In this initialization, because the fourth element is uninitialized, all elements that follow the
fourth element must be left uninitialized.
• Suppose that you have the following statement:
int x[5] = {};
Then some compilers may initialize each element of the array x 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 product or service 23
or otherwise on a password-protected website for classroom
Some Restrictions on Array Processing (1 of 2)
• Aggregate operation: any operation that manipulates the entire array as a single unit
• Example
int myList[5] = {0, 4, 8, 12, 16}; //initialized, array of 5
elements
int yourList[5]; //uninitialized array of 5 elements
yourList = myList; //illegal, can’t copy the whole array
yourList = yourList + myList; //illegal
Solution: To copy one array into another array, you must copy it component-wise
yourList[0] = myList[0]; yourList[1] = myList[1];
yourList[2] = myList[2]; yourList[3] = myList[3];
yourList[4] = myList[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 product or service 24
or otherwise on a password-protected website for classroom
Some Restrictions on Array Processing (2 of 2)
• Next, suppose that you want to read data into the array yourList. The following
statement is illegal and, in fact, would generate a syntax error:
• Example:
cin >> yourList; //illegal
• To read data into yourList, you must read one component at a time, using a loop
such as the following:
for (int index = 0; index < 5; index++)
cin >> yourList[index];
• Similarly, determining whether two arrays have the same elements and printing the
contents of an array must be done component-wise.
• The following statements are legal in the sense that they do not generate a syntax error;
however, they do not give the desired results.
cout << yourList;
if (myList <= yourList)
. ..
© 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 product or service 25
or otherwise on a password-protected website for classroom
Passing Individual Arrays Elements as Parameters to Functions (1 of 3)
• Individual Array elements used as actual parameters in a function call: Consider the
following function calls to two different functions to swap the numbers
1. mySwap1(x[i], x[i+1]);
2. mySwap2(x[i], x[i+1]);
Function mySwap1 cannot be used for swapping through function call as the
parameters are pass-by-value. Formal parameters a and b are local variables
in function mySwap1. They are swapped inside the function mySwap1
only so that swapping does not affect variables in the calling function.
© 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 product or service 26
or otherwise on a password-protected website for classroom
Passing Individual Arrays Elements as Parameters to Functions (2 of 3)
3 25 b
4 30 25
5 35
6 40
7 45
© 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 product or service 27
or otherwise on a password-protected website for classroom
Passing Individual Arrays Elements as Parameters to Functions (3 of 3)
5 35
6 40
7 45
© 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 product or service 28
or otherwise on a password-protected website for classroom
Passing Arrays as Parameters to Functions (1 of 2)
• We can also write functions that take entire arrays as actual and formal parameters.
• Only the base address of the array passed as actual argument (not the copy entire
array elements values or their addresses)
- This is what happens in pass-by-reference.
- As we are not passing a copy of the array – any changes to the array made within the function
(by modifying formal parameter) will also affect the original array (actual parameter)
• Being the default property of passing arrays by reference only to functions, therefore
do not need to use symbol & when declaring an array as a formal parameter
• The size of the one-dimensional array is also omitted when declaring an array as a
formal parameter
- If provided, it is ignored by the compiler
© 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 product or service 29
or otherwise on a password-protected website for classroom
Passing Arrays as Parameters to Functions (2 of 2)
• Arrays are passed as actual parameters by simply writing their name (brackets [] are
not required)
- The following example illustrates a function call, the sizes of both the arrays are unspecified
int listInt[10];
double listDouble[5];
funcArrayAsParam(listInt, listDouble); // function call
• The following example illustrates a function header, which includes an arrays as formal
parameter, the sizes of both the arrays are unspecified
void funcArrayAsParam(int listOne[], double listTwo[])
{
.
.
. Where are the arrays of formal parameters actually located?
}
• At the data area of the function that actually declared it these arrays.
• Suppose an array which stores students’ list registered in a particular course and the
number of elements in the array might increase or decrease as students drop or add that
course.
• To handle such situations, the programmers often declares an array large enough to hold
the largest possible list.
• The array has data in some initial array elements, but remaining array elements are
unused or hold invalid data and we want to process only those elemwnts of the array
that hold the actual data.
- The program is required to process the same array having varying lengths of data at
different times. How to specify the size of such an array for 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 product or service 31
or otherwise on a password-protected website for classroom
Partially Filled Arrays (2 of 2)
- The program keeps track of how many array elements are actually in use.
1. Declare and maintain a dedicated int variable to hold the actual list size. The
array can be processed by using a counter controlled for loop or while loop
const int MAXSIZE 10;
int myList[MAXSIZE] = {90, 85, 77, 86, 40];
int listSize = 5;
2. An array can be filled with valid values and indicate the end of actual values list
by placing a sentinel value after the last valid value in the array. The array can
be processed by using a sentinel while loop
const int MAXSIZE 10;
int myList[MAXSIZE] = {90, 85, 77, 86, 40, -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 product or service 32
or otherwise on a password-protected website for classroom
Partially Filled Arrays 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 product or service 33
or otherwise on a password-protected website for classroom
Constant Arrays as Formal Parameters (1 of 5)
• Recall that when a formal parameter is a reference parameter, then whenever the formal
parameter changes, the actual parameter changes as well.
• However, even though an array is always passed by reference, you can still prevent the
function from changing the actual parameter.
• Use const in the declaration of the formal parameter. This qualifier marks an array strictly as
input (i.e. read-only or input-only) parameter, rather than the default behaviors of both input as
well as output parameter
void example(int x[], const int y[], int sizeX, int sizeY);
Here, the function example can modify the array x, but not the array y.
Any attempt to change the array y inside the function example will result in a compile-time
error.
© 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 product or service 34
or otherwise on a password-protected website for classroom
Constant Arrays as Formal Parameters (2 of 5)
• These examples shows how to write functions for array processing and how to declare
an array as a formal parameter.
//Function to initialize an int array to 0.
//The array to be initialized and its size are passed as parameters.
//The parameter listSize specifies the number of elements to be initialized.
void initializeArray(int list[], int listSize)
{
for (int index = 0; index < listSize; index++)
list[index] = 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 product or service 35
or otherwise on a password-protected website for classroom
Constant Arrays as Formal Parameters (3 of 5)
//Function to print the elements of an int array.
//The array to be printed and the number of elements are passed as parameters.
//The parameter listSize specifies the number of elements to be printed.
void printArray(const int list[], int listSize)
{
for (int index = 0; index < listSize; index++)
cout << list[index] << " ";
}
//Function to find and return the sum of the elements of an int array.
//The parameter listSize specifies the number of elements to be added.
int sumArray(const int list[], int listSize)
{
int sum = 0;
for (int index = 0; index < listSize; index++)
sum = sum + list[index];
return sum;
}
© 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 product or service 36
or otherwise on a password-protected website for classroom
Constant Arrays as Formal Parameters (4 of 5)
//Function to find and return the index of the first largest element in an int array.
//The parameter listSize specifies the number of elements in the array.
int indexLargestElement(const int list[], int listSize)
{
int maxIndex = 0; //assume the first element is the largest
for (int index = 1; index < listSize; index++)
if (list[maxIndex] < list[index])
maxIndex = index;
return maxIndex;
}
© 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 product or service 37
or otherwise on a password-protected website for classroom
Constant Arrays as Formal Parameters (5 of 5)
//Function to copy some or all of the elements of one array into another array.
//Starting at the position specified by src, the elements of list1 are copied into list2
//starting at the position specified by tar.
//The parameter numOfElements specifies the number of elements of list1 to
//be copied into list2.
//Starting at the position specified by tar, the list2 must have enough components to copy the
//elements of list1.
//The following call copies all of the elements of list1 into the corresponding positions in list2:
//copyArray(list1, 0, list2, 0, numOfElements);
© 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 product or service 38
or otherwise on a password-protected website for classroom
Base Address of an Array and Array in Computer Memory (1 of 4)
• The base address of an array is the address (memory location) of the first array
component
• When an array is passed as a parameter, the base address of the actual array is passed to
the formal parameter:
int myList[5];
• The computer allocates five memory spaces, each
large enough to store an int value.
© 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 product or service 39
or otherwise on a password-protected website for classroom
Base Address of an Array and Array in Computer Memory (2 of 4)
the expression myList <= yourList evaluates to true if the base address of the
array myList is less than the base address of the array yourList; and evaluates to false
otherwise.
© 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 product or service 40
or otherwise on a password-protected website for classroom
Base Address of an Array and Array in Computer Memory (3 of 4)
- Each component of myList is of type int, so it uses four bytes to store a value.
- To access the value of myList[3], the computer calculates the address 1000 + 4 * 3 =
1000 + 12 = 1012. That is, this is the starting address of myList[3].
- So, starting at the address 1012, the computer accesses the next four bytes.
© 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 product or service 41
or otherwise on a password-protected website for classroom
Base Address of an Array and Array in Computer Memory (4 of 4)
• When you pass an array as a parameter, the base address of the actual array is also passed to
the formal parameter in function call.
int myList[5]; //Suppose, the base address of myList is 1000
// Also, suppose that you have the following call the function: arrayAsParameter
arrayAsParameter(myList, 5);
void arrayAsParameter(int list[], int size)
{
...
list[3] = 28; // Line 4, Also update the list element myList[3].
...
}
Statement of Line 4 stores 28 into list[3]. To access list[3], the computer calculates the
address as follows: 1000 + 4 * 3 = 1012. So, starting at the address 1012, the computer
accesses the next four bytes to access list[3]. As lists, list[3] and myList[3] refer
to the same memory location 1012, list[3] = 28 will also be updated myList[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 product or service 42
or otherwise on a password-protected website for classroom
Functions Cannot Return a Value of the Type Array (1 of 2)
• To do it properly if needed
• Example: While calling functions, input arrays and output arrays are passed the same way.
int x[3] = {1, 2, 3}, y[3] = {2, 3, 4}, x_plus_y[3];
add_arrays(x, y, x_plus_y, 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 product or service 43
or otherwise on a password-protected website for classroom
Functions Cannot Return a Value of the Type Array (2 of 2)
• The add_arrays function computes the sum by reading the corresponding elements from input
arrays ar1 and ar2, and then stores and returns the sum results as an output array arsum3.
© 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 product or service 44
or otherwise on a password-protected website for classroom
Other Ways to Declare Arrays
• In C++, you can create synonyms or aliases to a previously defined data type by using the
typedef statement.
Syntax : typedef existingTypeName newTypeName;
• In C++, typedef is a reserved word. The typedef statement does not create any new data
type; it creates only an alias to an existing data type.
• Example 1
const int SIZE = 50;
double list[SIZE];
• Example 2
const int SIZE = 50; //Line 1
typedef double list[SIZE]; //Line 2
list yourList; //Line 3
list myList; //Line 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 product or service 45
or otherwise on a password-protected website for classroom
Searching an Array for a Specific Item (1 of 4)
• 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
int seqSearch(const int list[], int listLength, int searchItem)
{
int loc;
bool found = false;
Use a flag-controlled
loc = 0;
while (loc < listLength && !found) { loop to keep track of
if (list[loc] == searchItem) whether the element
found = true; being searched found
else in an array or not.
loc++; }
if (found)
return loc;
else
return -1;
}
If the function seqSearch returns a value greater than or equal to
0, it is a successful search; otherwise, it is an unsuccessful search.
© 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 product or service 46
or otherwise on a password-protected website for classroom
Searching an Array for a Specific Item (2 of 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 product or service 47
or otherwise on a password-protected website for classroom
Searching an Array for a Specific Item (3 of 4)
int seqSearch(const int list[], int listLength, int searchItem)
{
int loc;
bool found = false;
loc = 0;
while (loc < listLength && !found)
if (list[loc] == searchItem)
found = true;
else
loc++;
if (found)
return loc;
else
return -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 product or service 48
or otherwise on a password-protected website for classroom
Searching an Array for a Specific Item (4 of 4)
• Simple
• If searchItem is at the bottom of the list, it will take many comparisons to find it.
• For sorted arrays, another search algorithm (binary search) is more efficient.
49
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (1 of 11)
• Selection Sort: rearrange the list by selecting an element and moving it to its proper
position
• Move it to the top of the unsorted portion by swapping with the element currently there
FIGURE 8-10 Elements of 1ist during the first iteration FIGURE 8-11 Elements of list during the second iteration
50
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (2 of 11)
51
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (3 of 11)
• Bubble Sort: Bubble sort is another classical sorting algorithm, which uses the “Bubble-
up” process multiple times to sort the array in ascending order.
• Bubble-up means move the largest element to the lowest position in the list and smallest
element to the highest position in the list
53
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (5 of 11)
• We want to rearrange, that is, sort, the elements of list in increasing order. The bubble
sort algorithm works as follows:
• In a series of N - 1 iterations, the successive elements list[index] and list[index +
1] of list are compared.
55
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (7 of 11)
56
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (8 of 11)
• For a list of length N, the bubble sort given previously makes exactly key comparisons and, on
average, about item assignments.
• Therefore, if N = 1000, to sort the list, bubble sort makes about 500,000 key comparisons
and about 250,000 item assignments.
57
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (9 of 11)
58
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (10 of 11)
• Note that the ordering can also be descending according to the application nature.
• For descending order, in the conditional statement replace > by < (bubble down)
59
© 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 product or service
or otherwise on a password-protected website for classroom
Sorting (11 of 11)
• In fact, these are not the only sorting algorithms. For example, Insertion Sort
• Some algorithms make more comparisons, whereas others make fewer item assignments.
• Also, there are algorithms that make fewer comparisons, as well as fewer item assignments.
• Analysis of the number of key comparisons and item assignments allows the user to decide which
algorithm to use in a particular situation.
60
© 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 product or service
or otherwise on a password-protected website for classroom
Auto Declaration and Range-Based for Loops (1 of 2)
Because the initializer, which is 15, is an int value, the type of num will be int.
© 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 product or service 61
or otherwise on a password-protected website for classroom
Auto Declaration and Range-Based for Loops (2 of 2)
• Range-based for loop: cont’d
double list[25];
double sum;
sum = 0; //line 1
for (double num : list) // line 2: read as “for each num in list”
sum = sum + num;
The variable num is initialized to contents of list[0]. In the next iteration, the value of
num is contents of list[1], and so on.
You can also use auto declaration in a range-based loop to process the elements of an array.
for (auto num : list)
{
if (max < num)
max = num;
}
© 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 product or service 62
or otherwise on a password-protected website for classroom
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];
• Declaration syntax
dataType arrayName[intExp1][intExp2];
• intExp1 and intExp2 are expressions with positive integer values specifying the number of
rows and columns in the array
arrayName[intExp1][intExp2];
• indexExp1 and indexExp2 are expressions with positive integer values, and specify the
row and column position
© 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 product or service 64
or otherwise on a password-protected website for classroom
Accessing Two-Dimensional Array Components
• If the data is provided in a list form, you can use one-dimensional arrays
• Two-dimensional arrays are used for data is that is in a table form
double sales[10][5];
double sales[10][5]; int i = 5;
sales[5][3] = 25.75; int j = 3;
sales[i][j] = 25.75;
• Elements of each row are enclosed within curly braces and separated by commas
• For number arrays, unspecified elements are set to 0.In this case, at least one of the
values must be given to initialize all the components of a 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 product or service 66
or otherwise on a password-protected website for classroom
Two-Dimensional Arrays and Enumeration Types (optional) (1 of 2)
• Enumeration types can be used effectively to make the program readable and easy to
manage. They can also 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 product or service 67
or otherwise on a password-protected website for classroom
Two-Dimensional Arrays and Enumeration Types (optional) (2 of 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 product or service 68
or otherwise on a password-protected website for classroom
Processing Two-Dimensional Arrays (1 of 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 product or service 69
or otherwise on a password-protected website for classroom
Processing Two-Dimensional Arrays (2 of 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 product or service 70
or otherwise on a password-protected website for classroom
Initialization
• An example initializing the entire matrix to 0, here use nested for loop
for (row = 0; row < NUMBER_OF_ROWS; row++)
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 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 product or service 71
or otherwise on a password-protected website for classroom
Print
© 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 product or service 72
or otherwise on a password-protected website for classroom
Input
• The following example shows how to find the sum of row number 4:
sum = 0;
row = 4;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum += matrix[row][col];
}
• The following example illustrates finding the sum of each individual row:
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
sum = 0;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum += matrix[row][col];
}
cout << "Sum of row " << row + 1 << " = " << sum << endl;
}
© 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 product or service 74
or otherwise on a password-protected website for classroom
Sum by Column
• The following example shows how to find the sum of column number 3:
sum = 0;
col = 3;
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
sum += matrix[row][col];
}
• The following example illustrates finding the sum of each individual column:
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum = 0;
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
sum += matrix[row][col];
}
cout << "Sum of column " << col + 1 << " = " << sum << endl;
}
© 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 product or service 75
or otherwise on a password-protected website for classroom
Sum of Whole Matrix Components
• The following example illustrates finding the sum of whole matrix components:
sum = 0;
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum += matrix[row][col];
}
}
cout << "Sum of matrix components" << " = " << sum << endl;
© 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 product or service 76
or otherwise on a password-protected website for classroom
Largest and Smallest Element in a 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 product or service 77
or otherwise on a password-protected website for classroom
Largest and Smallest Element in Each Row
• The following example finds the largest or smallest element in each row:
For (row = 0; row < NUMBER_OF_ROWS; row++)
{
largest = matrix[row][0];
smallest = matrix[row][0];
for (col = 1; col < NUMBER_OF_ROWS; col++)
{
if (matrix[row][col] > largest)
{
largest = matrix[row][col];
}
if (matrix[row][col] < smallest)
{
smallest = matrix[row][col];
}
}
cout << "The largest element in row " << row + 1
<< " = " << largest << endl;
cout << "The smallest element in row " << row + 1
<< " = " << smallest << endl;
}
© 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 product or service 78
or otherwise on a password-protected website for classroom
Largest and Smallest Element in a 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 product or service 79
or otherwise on a password-protected website for classroom
Largest and Smallest Element in Each 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 product or service 80
or otherwise on a password-protected website for classroom
Largest and Smallest Element in a Matrix
• The following example finds the largest and the smallest element in a Matrix:
//Assume the first element of the matrix is the largest.
largest = matrix[0][0];
smallest = matrix[0][0];
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
if (matrix[row][col] > largest)
{
largest = matrix[row][col];
}
}
}
cout << "The largest element in matrix “ << " = “
<< largest << endl;
cout << "The smallest element in matrix “ << " = “
<< smallest << endl;
© 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 product or service 81
or otherwise on a password-protected website for classroom
Passing Individual 2D Arrays Elements as Parameters to Functions
• Like 1D arrays, 2D individual array elements are treated as ordinary scalar variables, so
they can also be passed both by value and by reference as follows:
• Consider the following function calls to two different functions with 2D array elements
used as actual parameters:
1. int max = larger (x[i][j], x[i+1][j+1]);
2. myswap2(x[i][j], x[i+1][j+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 product or service 82
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (1 of 6)
• When storing a two-dimensional array in the computer’s memory, C++ uses the row
order form.
• That is, the first row is stored first, followed by the second row, followed by the third
row, and so on.
• Therefore, to compute the address of a component correctly, the compiler must know
where one row ends and the next row begins.
- Therefore, 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 product or service 83
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (2 of 6)
The following function prints the elements of each row of a two dimensional array
whose elements are of type int.
const int NUMBER_OF_ROWS = 6;
const int NUMBER_OF_COLUMNS = 5;
• During the function call, the number of columns of the actual parameter must match
the number of columns of 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 product or service 84
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (3 of 6)
The following function prints the elements of each row of a two dimensional array
whose elements are of type int.
void sumRows(int matrix[][NUMBER_OF_COLUMNS], int noOfRows)
{
int row, col;
int sum;
//Sum of each individual row
for (row = 0; row < noOfRows; row++)
{
sum = 0;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum = sum + matrix[row][col];
}
cout << "Sum of row " << (row + 1) << " = " << sum << endl;
}
}
© 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 product or service 85
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (4 of 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 product or service 86
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (5 of 6)
#include <iostream>
using namespace std;
const int NUMBER_OF_ROWS = 6;
const int NUMBER_OF_COLUMNS = 5;
void printMatrix(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
void sumRows(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
void largestInRows(int matrix[][NUMBER_OF_COLUMNS],int NUMBER_OF_ROWS);
int main()
{
int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]
= {{17, 8, 24, 10, 28}, {9, 20, 16, 55, 90},
{25, 45, 35, 8, 78}, {5, 0, 96, 45, 38},
{76, 30, 8, 14, 28}, {9, 60, 55, 62, 10}};
printMatrix(board, NUMBER_OF_ROWS);
cout << endl;
sumRows(board, NUMBER_OF_ROWS);
cout << endl;
largestInRows(board, NUMBER_OF_ROWS);
return 0;
}
//Place the definitions of the functions printMatrix, sumRows, and
// largestInRows as described previously here.
© 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 product or service 87
or otherwise on a password-protected website for classroom
Passing Two-Dimensional Arrays as Parameters to Functions (6 of 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 product or service 88
or otherwise on a password-protected website for classroom
Passing Partially-filled 2D Arrays as Parameters to Functions
• However, recall that the size of second dimension of the actual array MUST also be specified
void largestInRows(int matrix[][NUMBER_OF_COLUMNS], int noOfRows,
int noOfColumns)
{
int largest;
for (int row = 0; row < noOfRows; row++)
{
largest = matrix[row][0];
for (int col = 1; col < noOfColumns; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element of row " << (row + 1)
<< " = " << largest << endl;
}
}
© 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 product or service 89
or otherwise on a password-protected website for classroom
Another Way to Declare a Two-Dimensional Array (optional)
• The above previous statement defines a two-dimensional array data type tableType.
• Now we can declare variables of this type.
tableType matrix; // This statement declares an array of 20 rows and 10 columns:
• You can also use this data type when declaring formal parameters, as shown below:
void initialize(tableType table)
{
for (int row = 0; row < NUMBER_OF_ROWS; row++)
for (int col = 0; col < NUMBER_OF_COLUMNS; col++)
table[row][col] = 0;
}
By first defining a data type, you do not need to keep checking the
exact number of columns when you declare a two-dimensional array
as a variable or formal parameter, or when you pass an array as a
parameter during a function call.
© 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 product or service 90
or otherwise on a password-protected website for classroom
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 product or service 92
or otherwise on a password-protected website for classroom
Quick Review (2 of 2)
• In C++, C-strings are null terminated and are stored in character 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 product or service 93
or otherwise on a password-protected website for classroom
Home Assignment
1. Code Detection
94 94
© 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 product or service
or otherwise on a password-protected website for classroom
Programming Exercises
1. Write a program that takes an array named x as an input array from the user. Then,
create another array named y and copy the values from array x in reverse order.
- The program should copy the integers in x into y but in reverse order. i.e.,
3. Write a program to print all non-repeating elements of an array. Assume that array is
already sorted. (HINT: The common loop operation of keeping track of previous value
may help here). For example
- If the input array is {0, 5, 10, 10, 20, 25, 32, 32, 32, 40, 50, 50}, then output should be: {0 5 10
20 25 32 40 50 55}
95 95
© 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 product or service
or otherwise on a password-protected website for classroom
Programming Exercise 19
Airplane Seating Assignment: Write a program that can be used to assign seats for a
commercial airplane. The airplane has 13 rows, with six seats in each row. Rows 1 and 2
are first class, rows 3 through 7 are business class, and rows 8 through 13 are economy
class. Your program must prompt the user to enter the following information:
a. Ticket type (first class, business class, or economy class)
b. Desired seat
Output the seating plan in the following form: