Download presentation
Presentation is loading. Please wait.
Published byRose Wells Modified over 8 years ago
1
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 9: Arrays and Strings
2
C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index out of bounds” Become familiar with the restrictions on array processing Discover how to pass an array as a parameter to a function
3
C++ Programming: Program Design Including Data Structures, Fourth Edition3 Objectives (continued) Learn about C -strings 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
4
C++ Programming: Program Design Including Data Structures, Fourth Edition4 Data Types A data type is called simple if variables of that type can store only one value at a time A structured data type is one in which each data item is a collection of other data items
5
8.1 Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using [] operator const int ISIZE = 5; int tests[ISIZE];
6
Array Storage in Memory The definition int tests[ISIZE]; // SIZE is 5 allocates the following memory first element second element third element fourth element fifth element
7
Array Terminology In the definition int tests[ISIZE]; int is the data type of the array elements tests is the name of the array ISIZE, in [ISIZE], is the size declarator. It shows the number of elements in the array. The size of an array is the number of bytes allocated for it (number of elements) * (bytes needed for each element)
8
Array Terminology Examples Examples: Assumes int uses 4 bytes and double uses 8 bytes const int ISIZE = 5, DSIZE = 10; int tests[ISIZE]; // holds 5 ints, array // occupies 20 bytes double volumes[DSIZE]; // holds 10 doubles // array is 80 bytes
9
8.2 Accessing Array Elements Each array element has a subscript, used to access the element. Subscripts start at 0 subscripts 0 1 2 3 4
10
Accessing Array Elements Array elements (accessed by array name and subscript) can be used as regular variables tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; cout << tests; // illegal due to // missing subscript 0 1 2 3 4 tests
11
Array Subscripts Array subscript can be an integer constant, integer variable, or integer expression Examples: Subscript is cin >> tests[3]; int constant cout << tests[i]; int variable cout << tests[i+j]; int expression
12
8.4 Array Initialization Can be initialized during program execution with assignment statements tests[0] = 79; tests[1] = 82; // etc. Can be initialized at array definition with an initialization list const int ISIZE = 5; int tests[ISIZE] = {79,82,91,77,84};
13
Inputting and Displaying All Array Elements To access each element of an array −Use a loop −Let the loop control variable be the array subscript −A different array element will be referenced each time through the loop for (i = 0; i < 5; i++) cout << tests[i] << endl;
14
Sum of Array Elements Use a simple loop to add together array elements float average, sum = 0; for (int tnum=0; tnum< ISIZE; tnum++) sum += tests[tnum]; Once summed, average can be computed average = sum/5;
15
Partial Array Initialization If array is initialized at definition with fewer values than the size declarator of the array, remaining elements will be set to 0 or NULL int tests[ISIZE] = {79, 82}; Initial values used in order; cannot skip over elements to initialize noncontiguous range 7982000
16
Implicit Array Sizing Can determine array size by the size of the initialization list short quizzes[]={12,17,15,11}; Must use either array size declarator or initialization list when array is defined 12171511
17
Largest Array Element Use a loop to examine each element and find the largest element (i.e., one with the largest value) int largest = tests[0]; for (int tnum = 1; tnum < ISIZE; tnum++) { if (tests[tnum] > largest) largest = tests[tnum]; } cout << "Highest score is " << largest; A similar algorithm exists to find the smallest element
18
#include using namespace std; int main() { const int ISIZE=5; int tests[ISIZE]={9, 10, 8,11, 21}; int largest = tests[0]; for (int tnum = 1; tnum < ISIZE; tnum++) { if (tests[tnum] > largest) largest = tests[tnum]; } cout << "Highest score is " << largest; return 0; }
19
No Bounds Checking There are no checks in C++ that an array subscript is in range An invalid array subscript can cause program to overwrite other memory Example: const int ISIZE = 3; int i = 4; int num[ISIZE]; num[i] = 25; num [0] [1] [2] 25
20
Passing an Array Element Passing a single array element to a function is no different than passing a regular variable of that data type Function does not need to know the value it receives is coming from an array displayValue(score[i]); // call void displayValue(int item) // header { cout << item << endl; }
21
8.8 Arrays as Function Arguments To define a function that has an array parameter, use empty [] for array argument To pass an array to a function, just use the array name // Function prototype void showScores(int []); // Function header void showScores(int tests[]) // Function call showScores(tests);
22
Passing an Entire Array Just use array name, without any brackets, as the argument Can also pass array size so the function knows how many elements to process showScores(tests, 5); // call void showScores(int[], int); // prototype void showScores(int A[], int size) // header
23
#include using namespace std; int find_largest(int a[], int size){ int largest = a[0]; for (int i= 1; i < size; i++) { if (a[i] > largest) largest = a[i]; } return largest; } int main() { const int ISIZE=5; int tests[ISIZE]={9, 10, 8,11, 21}; int largest = find_largest(tests, ISIZE); cout << "Highest score is " << largest; return 0; }
24
Function with array parameter int find_largest(int a[], int size){ int largest = a[0]; for (int i= 1; i < size; i++) { if (a[i] > largest) largest = a[i]; } return largest; }
25
Problem: Update the program so that it finds if the array has an element equal to the number from the key board. Print out the index if it is found. int main(){ const int SIZE = 27; int i, num; int n[SIZE] = {11, 2, 14, 81, 27, 31,34, 13, 33, 91, 22, 45, 62, 8, 7, 9, 21, 28, 82,73, 91}; cin>>num; //read an number from key board return 0; }
26
#include using namespace std; int main(){ const int SIZE = 27; int i, num; int n[SIZE] = {11, 2, 14, 81, 27, 31,34, 13, 33, 91, 22, 45, 62, 8, 7, 9, 21, 28, 82,73, 91}; cin>>num; //read an number from key board for (i=0; i<SIZE; i++){ if (n[i]==num) cout<<" "<<i; } return 0; }
27
C++ Programming: Program Design Including Data Structures, Fourth Edition27 Arrays Array: a collection of a fixed number of components wherein all of the components have the same data type In a one-dimensional array, the components are arranged in a list form Syntax for declaring a one-dimensional array: intExp evaluates to a positive integer
28
C++ Programming: Program Design Including Data Structures, Fourth Edition28 Arrays (continued) Example: int num[5];
29
C++ Programming: Program Design Including Data Structures, Fourth Edition29 Accessing Array Components General syntax: where indexExp, called an index, is any expression whose value is a nonnegative integer Index value specifies the position of the component in the array [] is the array subscripting operator The array index always starts at 0
30
C++ Programming: Program Design Including Data Structures, Fourth Edition30 Accessing Array Components (continued)
31
C++ Programming: Program Design Including Data Structures, Fourth Edition31 Accessing Array Components (continued)
32
C++ Programming: Program Design Including Data Structures, Fourth Edition32 Accessing Array Components (continued)
33
C++ Programming: Program Design Including Data Structures, Fourth Edition33 Accessing Array Components (continued)
34
C++ Programming: Program Design Including Data Structures, Fourth Edition34 Processing One-Dimensional Arrays Some basic operations performed on a one- dimensional array are: −Initializing −Inputting data −Outputting data stored in an array −Finding the largest and/or smallest element Each operation requires ability to step through the elements of the array Easily accomplished by a loop
35
C++ Programming: Program Design Including Data Structures, Fourth Edition35 Processing One-Dimensional Arrays (continued) Consider the declaration int list[100]; //array of size 100 int i; Using for loops to access array elements: for (i = 0; i < 100; i++) //Line 1 //process list[i] //Line 2 Example: for (i = 0; i < 100; i++) //Line 1 cin >> list[i]; //Line 2
37
C++ Programming: Program Design Including Data Structures, Fourth Edition37 Array Index Out of Bounds If we have the statements: double num[10]; int i; The component num[i] is valid if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9 The index of an array is in bounds if the index >=0 and the index <= ARRAY_SIZE-1 −Otherwise, we say the index is out of bounds In C++, there is no guard against indices that are out of bounds
38
C++ Programming: Program Design Including Data Structures, Fourth Edition38 Array Initialization During Declaration Arrays can be initialized during declaration −In this case, it is not necessary to specify the size of the array Size determined by the number of initial values in the braces Example: double sales[] = {12.25, 32.50, 16.90, 23, 45.68};
39
C++ Programming: Program Design Including Data Structures, Fourth Edition39 Partial Initialization of Arrays During Declaration The statement: int list[10] = {0}; declares list to be an array of 10 components and initializes all of them to zero The statement: int list[10] = {8, 5, 12}; declares list to be an array of 10 components, initializes list[0] to 8, list[1] to 5, list[2] to 12 and all other components are initialized to 0
40
C++ Programming: Program Design Including Data Structures, Fourth Edition40 Partial Initialization of Arrays During Declaration (continued) The statement: int list[] = {5, 6, 3}; declares list to be an array of 3 components and initializes list[0] to 5, list[1] to 6, and list[2] to 3 The statement: int list[25]= {4, 7}; declares an array of 25 components; initializes list[0] to 4 and list[1] to 7 ; all other components are initialized to 0
41
C++ Programming: Program Design Including Data Structures, Fourth Edition41 Some Restrictions on Array Processing Consider the following statements: C++ does not allow aggregate operations on an array: Solution:
42
C++ Programming: Program Design Including Data Structures, Fourth Edition42 Some Restrictions on Array Processing (continued) The following is illegal too: Solution: The following statements are legal, but do not give the desired results:
43
C++ Programming: Program Design Including Data Structures, Fourth Edition43 Arrays as Parameters to Functions Arrays are passed by reference only The symbol & is not used when declaring an array as a formal parameter The size of the array is usually omitted −If provided, it is ignored by the compiler
44
C++ Programming: Program Design Including Data Structures, Fourth Edition44 Constant Arrays as Formal Parameters
45
C++ Programming: Program Design Including Data Structures, Fourth Edition45 Base Address of an Array and Array in Computer Memory The base address of an array is the address, or memory location of the first array component If list is a one-dimensional array, its base address is the address of list[0] When we pass an array as a parameter, the base address of the actual array is passed to the formal parameter
47
C++ Programming: Program Design Including Data Structures, Fourth Edition47 Functions Cannot Return a Value of the Type Array C++ does not allow functions to return a value of the type array
48
C++ Programming: Program Design Including Data Structures, Fourth Edition48 Integral Data Type and Array Indices C++ allows any integral type to be used as an array index Example:
49
C++ Programming: Program Design Including Data Structures, Fourth Edition49 Other Ways to Declare Arrays
50
C++ Programming: Program Design Including Data Structures, Fourth Edition50 C- Strings (Character Arrays) Character array: an array whose components are of type char C -strings are null-terminated ( '\0' ) character arrays Example: − 'A' is the character A − "A" is the C -string A "A" represents two characters, 'A' and '\0‘
51
C++ Programming: Program Design Including Data Structures, Fourth Edition51 C- Strings (Character Arrays) (continued) Consider the statement char name[16]; Since C -strings are null terminated and name has 16 components, the largest string that it can store has 15 characters If you store a string of length, say 10 in name −The first 11 components of name are used and the last five are left unused
52
C++ Programming: Program Design Including Data Structures, Fourth Edition52 C- Strings (Character Arrays) (continued) The statement char name[16] = "John"; declares an array name of length 16 and stores the C -string "John" in it The statement char name[] = "John"; declares an array name of length 5 and stores the C -string "John" in it
53
C++ Programming: Program Design Including Data Structures, Fourth Edition53 C- Strings (Character Arrays) (continued)
54
C++ Programming: Program Design Including Data Structures, Fourth Edition54 String Comparison C -strings are compared character by character using the collating sequence of the system If we are using the ASCII character set − "Air" < "Boat" − "Air" < "An" − "Bill" < "Billy" − "Hello" < "hello"
56
C++ Programming: Program Design Including Data Structures, Fourth Edition56 Reading and Writing Strings Most rules that apply to arrays apply to C - strings as well Aggregate operations, such as assignment and comparison, are not allowed on arrays Even the input/output of arrays is done component-wise The one place where C++ allows aggregate operations on arrays is the input and output of C -strings (that is, character arrays)
57
C++ Programming: Program Design Including Data Structures, Fourth Edition57 String Input cin >> name; stores the next input C - string into name To read strings with blanks, use get : cin.get(str, m+1); −Stores the next m characters into str but the newline character is not stored in str −If the input string has fewer than m characters, the reading stops at the newline character
58
C++ Programming: Program Design Including Data Structures, Fourth Edition58 String Output cout << name; 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 we will see strange output << continues to output data from memory adjacent to name until '\0' is found
59
C++ Programming: Program Design Including Data Structures, Fourth Edition59 Specifying Input/Output Files at Execution Time You can let the user specify the name of the input and/or output file at execution time:
60
C++ Programming: Program Design Including Data Structures, Fourth Edition60 string Type and Input/Output Files Argument to the function open must be a null-terminated string (a C -string) If we use a variable of type string to read the name of an I/O file, the value must first be converted to a C -string before calling open Syntax: strVar.c_str() where strVar is a variable of type string
61
C++ Programming: Program Design Including Data Structures, Fourth Edition61 Parallel Arrays Two (or more) arrays are called parallel if their corresponding components hold related information Example: int studentId[50]; char courseGrade[50];
62
C++ Programming: Program Design Including Data Structures, Fourth Edition62 Two-Dimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two dimensions −Sometimes called matrices or tables Declaration syntax: where intexp1 and intexp2 are expressions yielding positive integer values, and specify the number of rows and the number of columns, respectively, in the array
63
C++ Programming: Program Design Including Data Structures, Fourth Edition63 Two-Dimensional Arrays (continued)
64
C++ Programming: Program Design Including Data Structures, Fourth Edition64 Accessing Array Components Syntax: where indexexp1 and indexexp2 are expressions yielding nonnegative integer values, and specify the row and column position
65
C++ Programming: Program Design Including Data Structures, Fourth Edition65 Accessing Array Components (continued)
66
C++ Programming: Program Design Including Data Structures, Fourth Edition66 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, if all components of a row aren’t specified, unspecified ones are set to 0
67
C++ Programming: Program Design Including Data Structures, Fourth Edition67 Two-Dimensional Arrays and Enumeration Types
68
C++ Programming: Program Design Including Data Structures, Fourth Edition68 Processing Two-Dimensional Arrays Ways to process a two-dimensional array: −Process the entire array −Process a particular row of the array, called row processing −Process a particular column of the array, 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
69
C++ Programming: Program Design Including Data Structures, Fourth Edition69 Processing Two-Dimensional Arrays (continued)
70
C++ Programming: Program Design Including Data Structures, Fourth Edition70 Initialization To initialize row number 4 (i.e., fifth row) to 0 To initialize the entire matrix to 0:
71
C++ Programming: Program Design Including Data Structures, Fourth Edition71 Print To output the components of matrix :
72
C++ Programming: Program Design Including Data Structures, Fourth Edition72 Input To input data into each component of matrix :
73
C++ Programming: Program Design Including Data Structures, Fourth Edition73 Sum by Row To find the sum of row number 4 of matrix : To find the sum of each individual row:
74
C++ Programming: Program Design Including Data Structures, Fourth Edition74 Sum by Column To find the sum of each individual column:
75
C++ Programming: Program Design Including Data Structures, Fourth Edition75 Largest Element in Each Row and Each Column
76
C++ Programming: Program Design Including Data Structures, Fourth Edition76 Reversing Diagonal Before:
77
C++ Programming: Program Design Including Data Structures, Fourth Edition77 Reversing Diagonal (continued) To reverse both the diagonals:
78
C++ Programming: Program Design Including Data Structures, Fourth Edition78 Reversing Diagonal (continued) After:
79
C++ Programming: Program Design Including Data Structures, Fourth Edition79 Passing Two-Dimensional Arrays as Parameters to Functions Two-dimensional arrays can be passed as parameters to a function −Pass by reference Base address (address of first component of the actual parameter) is passed to formal parameter Two-dimensional arrays are stored in row order When declaring a two-dimensional array as a formal parameter, can omit size of first dimension, but not the second
80
C++ Programming: Program Design Including Data Structures, Fourth Edition80 Arrays of Strings Strings in C++ can be manipulated using either the data type string or character arrays ( C -strings) On some compilers, the data type string may not be available in Standard C++ (i.e., non-ANSI/ISO Standard C++)
81
C++ Programming: Program Design Including Data Structures, Fourth Edition81 Arrays of Strings and the string Type To declare 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
82
C++ Programming: Program Design Including Data Structures, Fourth Edition82 Arrays of Strings and C -Strings (Character Arrays)
83
C++ Programming: Program Design Including Data Structures, Fourth Edition83 Another Way to Declare a Two- Dimensional Array Consider the following: To declare an array of 20 rows and 10 columns:
84
Chapter 8 Starting Out with C++: Early Objects 5/e slide 84 © 2006 Pearson Education. All Rights Reserved 8.9 Two-Dimensional Arrays Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition int exams[4][3]; Number of rows Number of cols
85
Chapter 8 Starting Out with C++: Early Objects 5/e slide 85 © 2006 Pearson Education. All Rights Reserved Two-Dimensional Array Representation int exams[4][3]; Use two subscripts to access element exams[2][2] = 86; exams[0][0]exams[0][1]exams[0][2] exams[1][0]exams[1][1]exams[1][2] exams[2][0]exams[2][1]exams[2][2] exams[3][0]exams[3][1]exams[3][2] columns rowsrows
86
Chapter 8 Starting Out with C++: Early Objects 5/e slide 86 © 2006 Pearson Education. All Rights Reserved Initialization at Definition Two-dimensional arrays are initialized row- by-row int exams[2][2] = { {84, 78}, {92, 97} }; Can omit inner { } 8478 9297
87
Chapter 8 Starting Out with C++: Early Objects 5/e slide 87 © 2006 Pearson Education. All Rights Reserved Scan 2 D Array int a[Rows][Columns]={{ 10, 2, 3, 5}, {84, 23, 12, 7}, { 8, 13, 2, 7} }; int i, j, sum=0; for (i=0; i<Rows; i++){ for (j=0; j<Columns; j++) sum+=a[i][j]; };
88
Chapter 8 Starting Out with C++: Early Objects 5/e slide 88 © 2006 Pearson Education. All Rights Reserved #include using namespace std; const int Rows=3; //number of rows const int Columns=4; //number of columns int main() { int a[Rows][Columns]={{10, 2, 3, 5}, {84, 23, 12,7}, {8, 13, 2,7} }; int i, j, sum=0; for (i=0; i<Rows; i++){ for (j=0; j<Columns; j++) sum+=a[i][j]; }; cout<<“sum= "<<sum<<endl; return 0; }
89
Chapter 8 Starting Out with C++: Early Objects 5/e slide 89 © 2006 Pearson Education. All Rights Reserved Flow Chart to Scan Entire Array i=0 j=0 Access the element at row i and column j j++ j<number of columns? i++ i<number of rows?
90
Chapter 8 Starting Out with C++: Early Objects 5/e slide 90 © 2006 Pearson Education. All Rights Reserved Array 10 2 3 5 84 23 12 7 8 13 2 7
91
Chapter 8 Starting Out with C++: Early Objects 5/e slide 91 © 2006 Pearson Education. All Rights Reserved Two Loops variables i, and j for rows and columns resp.
92
Chapter 8 Starting Out with C++: Early Objects 5/e slide 92 © 2006 Pearson Education. All Rights Reserved Passing a Two-Dimensional Array to a Function Use array name as argument in function call getExams(exams, 2); Use empty [] for row and a size declarator for col in the prototype and header // Prototype, where NUM_COLS is 2 void getExams(int[][NUM_COLS], int); // Header void getExams (int exams[][NUM_COLS], int rows)
93
Chapter 8 Starting Out with C++: Early Objects 5/e slide 93 © 2006 Pearson Education. All Rights Reserved #include using namespace std; const int NUM_COLS = 4; // Number of columns in each array const int TBL1_ROWS = 3; // Number of rows in table1 void showArray(int [ ][NUM_COLS], int); // Function prototype int main(){ int table1[TBL1_ROWS][NUM_COLS] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}}; showArray(table1, TBL1_ROWS); return 0; }
94
Chapter 8 Starting Out with C++: Early Objects 5/e slide 94 © 2006 Pearson Education. All Rights Reserved void showArray(int array[ ][NUM_COLS], int numRows) { for (int row = 0; row < numRows; row++) {for (int col = 0; col < NUM_COLS; col++) { cout << setw(5) << array[row][col] << " "; } cout << endl; }
95
C++ Programming: Program Design Including Data Structures, Fourth Edition95 Multidimensional Arrays Multidimensional array: collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1) −Also called an n-dimensional array Declaration syntax: To access a component:
96
C++ Programming: Program Design Including Data Structures, Fourth Edition96 Multidimensional Arrays (continued) When declaring a multidimensional array as a formal parameter in a function −Can omit size of first dimension but not other dimensions As parameters, multidimensional arrays are passed by reference only A function cannot return a value of the type array There is no check if the array indices are within bounds
97
C++ Programming: Program Design Including Data Structures, Fourth Edition97 Programming Example: Code Detection When a message is transmitted in secret code over a transmission channel, it is usually transmitted as a sequence of bits (0s and 1s) Due to noise in the transmission channel, the transmitted message may become corrupted −Message received at destination is not the same as the message transmitted −Some of the bits may have been changed
98
C++ Programming: Program Design Including Data Structures, Fourth Edition98 Programming Example: Code Detection (continued) Several techniques to check the validity of the transmitted message at the destination One technique is to transmit the same message twice −At the destination, both copies of the message are compared bit by bit −If the corresponding bits are the same, the message received is error-free
99
C++ Programming: Program Design Including Data Structures, Fourth Edition99 Programming Example: Code Detection (continued) We write a program to check if the message received at the destination is error-free For simplicity, assume that: −The secret code representing the message is a sequence of digits (0 to 9) −The maximum length of the message is 250 digits The first number in the message is the length of the message
100
C++ Programming: Program Design Including Data Structures, Fourth Edition100 Programming Example: Code Detection (continued) If the secret code is 7 9 2 7 8 3 5 6 then the message is seven digits long The above message is transmitted (twice) as 7 9 2 7 8 3 5 6 Input: a file containing the secret code and its copy Output: the secret code, its copy, and a message if the received code is error-free
101
C++ Programming: Program Design Including Data Structures, Fourth Edition101 Programming Example: Code Detection (continued) The results are output in the following form: Code DigitCode Digit Copy 9 2 7 8 3 5 6 Message transmitted OK
102
C++ Programming: Program Design Including Data Structures, Fourth Edition102 Programming Example: Problem Analysis Because we have to compare digits of the secret code and its copy: −First, read the secret code and store it in an array −Next, read first digit of the copy and compare it with the first digit of the code, and so on −If any corresponding digits are not the same, print a message next to the digits The first number in the secret code, and in the copy, indicates the length of the code
103
C++ Programming: Program Design Including Data Structures, Fourth Edition103 Programming Example: Algorithm Design Open the input and output files If the input file does not exist, exit the program Read the length of the secret code If the length of the secret code is greater than 250, terminate the program because the maximum length of the code in this program is 250 Read and store the secret code into an array
104
C++ Programming: Program Design Including Data Structures, Fourth Edition104 Programming Example: Algorithm Design (continued) Read the length of the copy If the length of the secret code and its copy are the same, compare the codes; otherwise, print an error message Note: To simplify function main, write a function, readCode, to read the secret code and another function, compareCode, to compare the codes
105
C++ Programming: Program Design Including Data Structures, Fourth Edition105 Programming Example: readCode First, read length of secret code If length of secret code is greater than 250 −Set lenCodeOk (a reference parameter) to false and the function terminates Value of lenCodeOk is passed to calling function to indicate if secret code was read successfully If length of code is less than 250, readCode reads and stores secret code into an array
106
C++ Programming: Program Design Including Data Structures, Fourth Edition106 Programming Example: readCode (continued)
107
C++ Programming: Program Design Including Data Structures, Fourth Edition107 Programming Example: compareCode Set a bool variable codeOk to true If length of code and copy are not equal −Output error message and terminate function For each digit in input file −Read the next digit of secret code copy −Output digits from code and copy −If corresponding digits are not equal, output error message and set codeOk to false If codeOk, output message indicating code transmitted OK, else output an error message
108
C++ Programming: Program Design Including Data Structures, Fourth Edition108 Programming Example: compareCode (continued)
109
C++ Programming: Program Design Including Data Structures, Fourth Edition109 Programming Example: compareCode (continued)
110
C++ Programming: Program Design Including Data Structures, Fourth Edition110 Programming Example: Main Algorithm Declare variables Open the files Call readCode to read the secret code If (length of the secret code <= 250) −Call compareCode to compare the codes else −Output an appropriate error message
111
Chapter 8 Starting Out with C++: Early Objects 5/e slide 111 © 2006 Pearson Education. All Rights Reserved Bubble Sort Algorithm 1.Compare 1 st two elements and exchange them if they are out of order. 2.Move down one element and compare 2 nd and 3 rd elements. Exchange if necessary. Continue until end of array. 3.Pass through array again, repeating process and exchanging as necessary. 4.Repeat until a pass is made with no exchanges.
112
Chapter 8 Starting Out with C++: Early Objects 5/e slide 112 © 2006 Pearson Education. All Rights Reserved Bubble Sort Example Array numlist3 contains Compare values 17 and 23. In correct order, so no exchange. Compare values 23 and 11. Not in correct order, so exchange them. 1723511 Compare values 23 and 5. Not in correct order, so exchange them.
113
Chapter 8 Starting Out with C++: Early Objects 5/e slide 113 © 2006 Pearson Education. All Rights Reserved Bubble Sort Example Array numlist3 contains Compare values 23 and 11. Not in correct order, so exchange them. 1752311
114
Chapter 8 Starting Out with C++: Early Objects 5/e slide 114 © 2006 Pearson Education. All Rights Reserved Bubble Sort Example Array numlist3 contains Compare values 23 and 11. Not in correct order, so exchange them. 1751123
115
Chapter 8 Starting Out with C++: Early Objects 5/e slide 115 © 2006 Pearson Education. All Rights Reserved Bubble Sort Example (continued) After first pass, array numlist3 contains Compare values 17 and 23. In correct order, so no exchange. 5171123 Compare values 17 and 11. Not in correct order, so exchange them. In order from previous pass
116
Chapter 8 Starting Out with C++: Early Objects 5/e slide 116 © 2006 Pearson Education. All Rights Reserved Bubble Sort Example (continued) After second pass, array numlist3 contains No exchanges, so array is in order Compare values 5 and 11. In correct order, so no exchange. Compare values 17 and 23. In correct order, so no exchange. 5111723 Compare values 11 and 17. In correct order, so no exchange. In order from previous passes
117
Chapter 8 Starting Out with C++: Early Objects 5/e slide 117 © 2006 Pearson Education. All Rights Reserved Bubble Sort Tradeoffs Benefit −Easy to understand and implement Disadvantage −Inefficiency make it slow for large arrays
118
Chapter 8 Starting Out with C++: Early Objects 5/e slide 118 © 2006 Pearson Education. All Rights Reserved #include using namespace std; void sortArray(int [], int); void showArray(int [], int); int main(){ const int SIZE = 6; int values[SIZE] = {7, 2, 3, 8, 9, 1}; cout << "The unsorted values are:\n"; showArray(values, SIZE); sortArray(values, SIZE); cout << "The sorted values are:\n"; showArray(values, SIZE); return 0; }
119
Chapter 8 Starting Out with C++: Early Objects 5/e slide 119 © 2006 Pearson Education. All Rights Reserved void sortArray(int array[ ], int elems){ int temp; bool swap; do{ swap = false; for (int count = 0; count < (elems - 1); count++){ if (array[count] > array[count + 1]){ temp = array[count]; array[count] = array[count + 1]; array[count + 1] = temp; swap = true; } } while (swap); }
120
Chapter 8 Starting Out with C++: Early Objects 5/e slide 120 © 2006 Pearson Education. All Rights Reserved void showArray(int array[ ], int elems) { for (int count = 0; count < elems; count++) cout << array[count] << " "; cout << endl; }
121
Chapter 8 Starting Out with C++: Early Objects 5/e slide 121 © 2006 Pearson Education. All Rights Reserved Problem: Change the bubble sorting function in the last slide so that it sorts the elements by decreasing order.
122
Chapter 8 Starting Out with C++: Early Objects 5/e slide 122 © 2006 Pearson Education. All Rights Reserved void sortArray(int array[ ], int elems){ int temp; bool swap; do{ swap = false; for (int count = 0; count < (elems - 1); count++){ if (array[count] < array[count + 1]){ temp = array[count]; array[count] = array[count + 1]; array[count + 1] = temp; swap = true; } } while (swap); }
123
Chapter 8 Starting Out with C++: Early Objects 5/e slide 123 © 2006 Pearson Education. All Rights Reserved Linear Search Algorithm Search the elements in the array from left to right. If search value is found, then return the position. Array: 23 5112293 Search value: 11
124
Chapter 8 Starting Out with C++: Early Objects 5/e slide 124 © 2006 Pearson Education. All Rights Reserved Linear Search Algorithm Set found to false Set position to –1 Set index to 0 While index < number of elts and found is false If list [index] is equal to search value found = true position = index End If Add 1 to index End While Return position
125
Chapter 8 Starting Out with C++: Early Objects 5/e slide 125 © 2006 Pearson Education. All Rights Reserved Linear Search Example Array numlist contains Searching for the the value 11, linear search examines 17, 23, 5, and 11 Searching for the the value 7, linear search examines 17, 23, 5, 11, 2, 29, and 3 17235112293
126
Chapter 8 Starting Out with C++: Early Objects 5/e slide 126 © 2006 Pearson Education. All Rights Reserved Linear Search int linearSearch(const int array[ ],int key, int size ) { int n; for ( n = 0; n <= size - 1; ++n ) if ( array[ n ] == key ) return n; return -1; }
127
Chapter 8 Starting Out with C++: Early Objects 5/e slide 127 © 2006 Pearson Education. All Rights Reserved Linear Search Tradeoffs Benefits −Easy algorithm to understand −Array can be in any order Disadvantage −Inefficient (slow): for array of N elements, examines N/2 elements on average for value in array, N elements for value not in array
128
Chapter 8 Starting Out with C++: Early Objects 5/e slide 128 © 2006 Pearson Education. All Rights Reserved Binary Search Algorithm 1.Divide a sorted array into three sections. −middle element −elements on one side of the middle element −elements on the other side of the middle element 2.If the middle element is the correct value, done. Otherwise, go to step 1, using only the half of the array that may contain the correct value. 3.Continue steps 1 and 2 until either the value is found or there are no more elements to examine.
129
Chapter 8 Starting Out with C++: Early Objects 5/e slide 129 © 2006 Pearson Education. All Rights Reserved Binary Search A[ ] left A[m/2] right if (value==A[m/2]) it is found if (value<A[m/2]) search in the left side else search in the right side
130
Chapter 8 Starting Out with C++: Early Objects 5/e slide 130 © 2006 Pearson Education. All Rights Reserved Search Linear search in arbitrary array: Reduce search region by 1 each checking Binary search in sorted array: Reduce search region by half each checking
131
Chapter 8 Starting Out with C++: Early Objects 5/e slide 131 © 2006 Pearson Education. All Rights Reserved Binary Search Example Array numlist2 contains Searching for the the value 11, binary search examines 11 and stops Searching for the the value 7, binary search examines 11, 3, 5, and stops 23511172329
132
Chapter 8 Starting Out with C++: Early Objects 5/e slide 132 © 2006 Pearson Education. All Rights Reserved Search 7 2 3 5 11 17 23 29 2 3 1
133
Chapter 8 Starting Out with C++: Early Objects 5/e slide 133 © 2006 Pearson Education. All Rights Reserved Binary Search Tradeoffs Benefit −Much more efficient than linear search (For array of N elements, performs at most log 2 N comparisons) Disadvantage −Requires that array elements be sorted
134
Chapter 8 Starting Out with C++: Early Objects 5/e slide 134 © 2006 Pearson Education. All Rights Reserved #include using namespace std; int binarySearch(int [ ], int, int); // Function prototype const int SIZE = 20; int main(){ int tests[SIZE] = {101,142,147,189,199, 207, 222, 234,289,296, 310,319,388,394,417,429,447,521,536, 600}; int results, empID; cout << "Enter the employee ID you wish to search for: "; cin >> empID; results = binarySearch(tests, SIZE, empID); cout<<result; return 0; }
135
Chapter 8 Starting Out with C++: Early Objects 5/e slide 135 © 2006 Pearson Education. All Rights Reserved int binarySearch(int array[ ], int numElems, int value){ int first = 0, // First array element last = numElems - 1, // Last array element middle, // Midpoint of search position = -1; // Position of search value bool found = false; // Flag while (!found && first <= last){ middle = (first + last) / 2; // Calculate midpoint if (array[middle] == value) // If value is found at mid { found = true; position = middle; } else if (array[middle] > value) // If value is in lower half last = middle - 1; else first = middle + 1; // If value is in upper half } return position; }
136
Chapter 8 Starting Out with C++: Early Objects 5/e slide 136 © 2006 Pearson Education. All Rights Reserved Problem Use binary search to find 388 among 101,142,147,189,199, 207, 222, 234,289,296, 310,319,388,394,417,429,447,521,536, 600
137
C++ Programming: Program Design Including Data Structures, Fourth Edition137 Summary Array: 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
138
C++ Programming: Program Design Including Data Structures, Fourth Edition138 Summary (continued) The base address of an array is the address of the first array component When passing an array as an actual parameter, you use only its name −Passed by reference only A function cannot return a value of the type array In C++, C -strings are null terminated and are stored in character arrays
139
C++ Programming: Program Design Including Data Structures, Fourth Edition139 Summary (continued) Commonly used C -string manipulation functions include: − strcpy, strcmp, and strlen Parallel arrays are used to hold related information In a two-dimensional array, the elements are arranged in a table form
140
C++ Programming: Program Design Including Data Structures, Fourth Edition140 Summary To access an element of a two-dimensional array, you need a pair of indices: −One for the row position −One for the 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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.