Copyright © 2012 Pearson Education, Inc. Chapter 7 One Dimensional Arrays.
-
Upload
rosalyn-horn -
Category
Documents
-
view
218 -
download
5
Transcript of Copyright © 2012 Pearson Education, Inc. Chapter 7 One Dimensional Arrays.
Copyright © 2012 Pearson Education, Inc.
OutlineObjectives
1. Arrays
2. Problem Solving Applied: Hurricane Categories
3. Statistical Measurements
4. Problem Solving Applied: Speech Signal Analysis
5. Sorting and Search Algorithms
6. Problem Solving Applied: Tsunami Warning Systems
7. Character Strings
8. The string class
9. The vector class
10.Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
ObjectivesDevelop problem solutions in C++ containing:• One-dimensional arrays and vectors• Programmer-defined modules for statistical analysis of
data• Functions that sort data and search data• Functions that calculate the probability of an event• Character strings and string objects• Functions defined in the header files cstring and string• Custom header files
Arrays Defined
• An array is a data structure for storing a contiguous block of data.
• All data elements in an array must be of the same type.
• Individual elements of the array are specified using the array name and an offset.
• In C++ the offset of the first element is always 0 (zero).
Copyright © 2012 Pearson Education, Inc.
Array Definition Syntax
Copyright © 2012 Pearson Education, Inc.
Syntax:data_type identifier[ [array_size] ] [= initialization_list ]; //array_size must be an integer constant
Examplesint data[5]; //allocates consecutive memory for 5 integer valueschar vowels[5] = {‘a', ‘e', ‘i', ‘o', ‘u'}; //allocates and initializesdouble t[100] = {0.0}; //allocates and initialized all values to 0.0
Valid Referencescout << vowels[0];cout << t[2];
Invalid Referencescout << vowel[5]; //invalid offset.cout << t[-1]; //invalid offset
7
Initializing Arrays
Initializing array elements (initialization=>declaration)char vowels[5] = {'a', 'e', 'i', 'o', 'u'};bool ansKey[] ={true, true, false, true, false, false};char word[] = "Hello";
vowels'a' 'e' 'i' 'o' 'u'
true falsefalsetruefalsetrue
ansKey
word'H' 'e' 'l' 'l' 'o' '\0'
Accessing Array Elements
• Offsets are used to access individual elements of an array.
• General format:array_identifier[offset]
• Examplefor (int i=0; i<=7; ++i)m[i] = double(i) + 0.5;
• Integer expressions may be used as offsets.– i.e. offset does not need to be constant
Copyright © 2012 Pearson Education, Inc.
Avoiding Bugs
• C++ does not enforce array bounds!– Invalid references are NOT reported by the
compiler.– May or may not result in run-time error.
• E.g. segmentation fault, bus error, etc.• More often than not no run-time error occurs.
– Such errors are often difficult to identify.– Results in unpredictable program behavior.
Copyright © 2012 Pearson Education, Inc.
Operator Precedence
Copyright © 2012 Pearson Education, Inc.
Precedence Operator Associativity
1 () [] Innermost First
2 Unary operators: + - ++ -- ! (type) Right to left
3 * / % Left to right
4 + - Left to right
5 < <= > => Left to right
6 == != Left to right
7 && Left to right
8 || Left to right
9 ? : Right to left
10 = += -= *= /= %= Right to left
11 , Left to right
Functions and Arrays
• An array identifier, without subscripts, references the starting address(first element) of the array.
• In C++, arrays are passed by reference (i.e. the starting address is passed, no size information)
• Arrays in C++ do not know their size.
• Generally we specify an additional parameter representing the number of elements in the array.
Copyright © 2012 Pearson Education, Inc.
Example
#include <iostream>using namespace std;const int MAXSIZE=20;void ReadArr(double a[], int& count, istream& in);int FindMin(const double a[], int count);
int main() { double darr[MAXSIZE]; int cnt=0, position=0; ReadArr(darr, cnt, cin); position = FindMin(darr, cnt); cout << "The smallest value in the array is " << darr[position] << endl;}
Copyright © 2012 Pearson Education, Inc.
Example
// This function inputs values into an array until EOF // or array limit reachedvoid ReadArray(double a[], int& count, istream& in) {
double temp;count = 0;in >> temp;while ( (count < MAXSIZE) && !in.eof() ) {
a[count] = temp;++count;in >> temp;
}}
Copyright © 2012 Pearson Education, Inc.
Example
//This function returns the offset of the smallest//value in an array
int FindMin(const double a[], int size) { int offsetOfMin = 0;
for (int i=1; i<size; ++i) {if (a[i] < a[offsetOfMin] ) {
offsetOfMin = i; } //end if } //end for
return offsetOfMin;} //end FindMin
Copyright © 2012 Pearson Education, Inc.
Hurricane Categories
• The Saffir-Simpson scale of hurricane intensities is used to classify hurricanes according to the amount of damage that the storm is likely to generate if it hits a populated area.
Copyright © 2012 Pearson Education, Inc.
CategoryWind Speed
(mph)Storm Surge
(feet)Expected Property
Damage
1 74-95 4-5 Minimal
2 96-110 6-8 Moderate
3 111-130 9-12 Extensive
4 131-155 13-18 Extreme
5 155+ 18+ Catastrophic
Statistical Measurements
• Data collected from engineering experiments often have statistical properties that change from one data set to another.– E.g. sin(60) is always the same, but the miles
per gallon a vehicle consumes varies depending on type of driving, temperature, etc…
Copyright © 2012 Pearson Education, Inc.
Simple Statistical Analyses
• Simple statistical analyses often involve computing properties of a data set such as:– Minimum value– Maximum value– Mean (average) value– Median (middle) value
Copyright © 2012 Pearson Education, Inc.
Recall…
//This function returns the offset of the smallest//value in an array
int FindMin(const double a[], int size) { int offsetOfMin = 0; for (int i=1; i<size; ++i) { if (a[i] < a[offsetOfMin] ) { offsetOfMin = i; } //end if } //end for return offsetOfMin;} //end FindMin
Copyright © 2012 Pearson Education, Inc.
Question
• Given the previous algorithm for finding the offset of the minimum element of a data set, how can you modify it to find:– The offset of maximum element?– The value of the minimum element?– The value of the maximum element?
Copyright © 2012 Pearson Education, Inc.
Offset of Maximum
//This function returns the offset of the smallest//value in an array
int FindMin(const double a[], int size) { int offsetOfMin = 0; for (int i=1; i<size; ++i) { if (a[i] > a[offsetOfMin] ) { offsetOfMin = i; } //end if } //end for return offsetOfMin;} //end FindMin
Copyright © 2012 Pearson Education, Inc.
Simply changing the relational operator in the FindMin algorithm with yield an algorithm that finds the offset of the maximum value!Note that identifiers are not meaningful to the compiler… identifiers are used only to uniquely identify (and type) variables.
Min and Max Offsets
//This function returns the //offset of the smallest//value in an array
int FindMin(const double a[], int size) { int offsetOfMin = 0; for (int i=1; i<size; ++i) { if (a[i] < a[offsetOfMin] ) { offsetOfMin = i; } //end if } //end for return offsetOfMin;} //end FindMin
Copyright © 2012 Pearson Education, Inc.
//This function returns the //offset of the largest//value in an array
int FindMax(const double a[], int size) { int offsetOfMax = 0; for (int i=1; i<size; ++i) { if (a[i] > a[offsetOfMax] ) { offsetOfMax = i; } //end if } //end for return offsetOfMax;} //end FindMax
Min and Max Values
//This function returns the //value of the smallest//element in an array
double FindMinVal(const double a[], int size) { int offsetOfMin = 0; for (int i=1; i<size; ++i) { if (a[i] < a[offsetOfMin] ) { offsetOfMin = i; } //end if } //end for return a[offsetOfMin];} //end FindMinVal
Copyright © 2012 Pearson Education, Inc.
//This function returns the //value of the largest//element in an array
double FindMaxVal(const double a[], int size) { int offsetOfMax = 0; for (int i=1; i<size; ++i) { if (a[i] > a[offsetOfMax] ) { offsetOfMax = i; } //end if } //end for return a[offsetOfMax];} //end FindMaxVal
Min and Max Values
//This function returns the //value of the smallest//element in an array
double FindMinVal(const double a[], int size) { return a[FindMin(a,size)];} //end FindMinVal
Copyright © 2012 Pearson Education, Inc.
//This function returns the //value of the largest//element in an array
double FindMaxVal(const double a[], int size) { return a[FindMax(a,size)];} //end FindMaxVal
Computing the Mean
//This function computes the mean of a dataset //contained in an array. // Mean = Sum(all array elements)/sizedouble Mean(const double a[], int size) { double sum(0);
//compute the sum for (int i=0; i<size; ++i) sum += a[i];
//return the mean return sum/size;} //end Mean
Copyright © 2012 Pearson Education, Inc.
Variance
• One of the most important statistical measurements for a data set is variance.
where σ2 is the variance and μ is the mean of all values x0, x1, … , xn-1.
Note – standard deviation is just σ.Copyright © 2012 Pearson Education, Inc.
Computing the Variance
//This function computes the variance of a dataset//contained in an array.
double Variance(const double a[], int n) { double sum(0), mu = mean(a,n);
//compute the sum for (int i=0; i<n; ++i) sum += (a[i]-mu)*(a[i]-mu);
//return the mean return sum/(n-1);} //end Variance
Copyright © 2012 Pearson Education, Inc.
Custom Header Files
• Frequently used classes and functions may be stored in separate files to easily include them in other programs.
• Define code ‘libraries’• Header file named “library_name.h”• Implementation file named “library_name.cpp”• To use the library, #include “library_name.h” and
be sure the linker can find the implementation file.
Copyright © 2012 Pearson Education, Inc.
stat_lib.h
//This header defines commonly used statistical //functions
#pragma once
int FindMin(const double [], int);int FindMax(const double [], int);double FindMinVal(const double [], int);double FindMaxVal(const double [], int);double Mean(const double [], int);double Variance(const double [], int);double StandardDeviation(const double [], int);
Copyright © 2012 Pearson Education, Inc.
Sorting Algorithms
• Sorting algorithms arrange the data into either ascending or descending order, based on the values in the array.
• Sorting algorithms to be discussed– Selection sort
Copyright © 2012 Pearson Education, Inc.
Selection Sort Algorithm
• Find minimum value, place it in the first position.
• Find next minimum value, place it in the second position.
• Continue doing this until you have placed the second to the largest value in the second to the last position.
Copyright © 2012 Pearson Education, Inc.
Selection Sort//This function sorts the array with n elements//into ascending order using selection sortvoid Sort(const double a[], int n) { double temp; int m; for (int k=0; k<=n-2; ++k) { //find position of smallest element beginning at k m = k; for (int j=k+1; j < n-1; ++j) if (a[j] < a[m]) m = j; //exchange smallest value with value at k temp = x[m]; x[m] = x[k]; x[k] = temp; } //end for (k)} //end Sort
Copyright © 2012 Pearson Education, Inc.
Searching Algorithms
• Search algorithms are groupedaccording to those that required an ordered dataset and those that do not (i.e. unordered datasets).– Unordered datasets searched sequentially.– Ordered datasets may be searched
sequentially, however binary searches are more efficient.
Copyright © 2012 Pearson Education, Inc.
Searching Unordered Datasets
• Simple Sequential Search– Examine each element starting with the first one until:
• a match is found.• end of the list is reached.
• Sequential search can be implemented as:– a function which returns true if item in the list, false if
item is not in the list.– a function which returns the location of the item if
found, or –1 if not found.
Copyright © 2012 Pearson Education, Inc.
Searching Ordered Datasets
• Modified Sequential Search:– examine every element in the list until:
• item is found.• list element is larger/smaller than the item you are searching
for (search fails).
• Binary Search– Examine middle element:
• if element equals item, item found, return location.• if element is larger than item ignore bottom of list.• if element is smaller than item ignore top of list.
– Repeat until:• item is found.• top and bottom cross over (search failed).
Copyright © 2012 Pearson Education, Inc.
Example of Binary Search for 48
Copyright © 2012 Pearson Education, Inc.
7059564337282214115arr[top] arr[bot]
arr[mid] arr[bot]arr[top]
4337arr[top] arr[bot]
mid is 5
43arr[6]
arr[mid]
mid is 6
mid is 7 7059564337
43
arr[top]arr[bot]
C-style Character Strings
• A C style strings is defined as a sequence of characters, terminated by the null character.
• When declaring a character array to store a C style string, memory must be allocated for the null character ('\0').
• Literal string constants are enclosed within double quote marks: "a string".
Copyright © 2012 Pearson Education, Inc.
C-style String Input• Recall that the input operator (>>) skips
whitespace .• To input strings with embedded whitespace , the
getline() function can be used as illustrated:char phrase[SIZE];cin.getline(phrase, SIZE);
• The getline() function reads up to SIZE-1 characters from the input stream and will insert the null character.
• getline() is a member function of what class?
Copyright © 2012 Pearson Education, Inc.
C-style String Functions• The Standard C++ library contains a set of
predefined functions that operate on C style strings.
• These functions are defined in the header file:cstring
• Commonly used string functions:– strlen()– strcpy()– strcat()– strcmp()
Copyright © 2012 Pearson Education, Inc.
C-style String Example
#include <iostream>#include <cstring> //strcmp(), strcpy(), strcat()uses namespace std;void main() { char str1[30] = "John", str2[30] = "Johnson"; char phrase[20] = "'s shirt was green", sentence[30]; if (strcmp(str1,str2) < 0) strcpy (sentence, str1);//puts "John" into sentence else strcpy (sentence,str2);//puts "Johnson” into sentence strcat(sentence, phrase);//append phrase to sentence cout << "Sentence is: " << sentence << endl;}
Copyright © 2012 Pearson Education, Inc.
Avoiding Bugs• The null character ( ‘\0’ ) must always
mark the end of the string.– If there is no null character, functions will
produce invalid references that can be difficult to identify (remember that C-style strings are 1D arrays of characters).
• String sizes are fixed.– Input operator does NOT ‘know’ what the array
size is; input may result in overflow of the array (invalid references).
Copyright © 2012 Pearson Education, Inc.
The String Class
• The string class implements the concept of a character string.
• A string object can increase and decrease its size dynamically.
• Numerous operators and methods are defined in the string class.
Copyright © 2012 Pearson Education, Inc.
Common Methods of the string Class
– size( )– empty( )– substr (int start, int len)– c_str()
Copyright © 2012 Pearson Education, Inc.
Operators Overloaded for the string Class
• relational operators – < > == <= >=
• concatenation– + +=
• assignment– =
Copyright © 2012 Pearson Education, Inc.
String Class Example
#include <iostream>#include <string> //string classuses namespace std;void main() { string str1 = "John", str2 = "Johnson"; string phrase = "'s shirt was green", sentence; if ( str1< str2 ) sentence = str1;//puts "John" into sentence else sentence = str2;//puts "Johnson” into sentence sentence += phrase; //append phrase to sentence cout << "Sentence is: " << sentence << endl;}
Copyright © 2012 Pearson Education, Inc.
The vector Class
• Predefined type included in theStandard Template Library
• Provides a generic implementation of the array concept.
• Vectors can increase and decrease its size dynamically.
• Numerous operators and methods are defined on vectors.
Copyright © 2012 Pearson Education, Inc.
vector Examples
vector<char> v1;
//Define vector of type char, capacity 0.
vector<int> v2(10);
//Define v2 with capacity for 10 integers.
vector<string> v3(n);
//Define v3 with capacity for n strings.
vector<double> v4(n,1.0);
//Define v4 with capacity for n doubles.
//Initialize each element to 1.0.
Copyright © 2012 Pearson Education, Inc.
Common Methods of the vector Class
– back()– begin()– capacity()– empty( )– end()– erase()– insert()– pop_back()– pop_front()– resize( ) – size( )
Copyright © 2012 Pearson Education, Inc.
Passing string and vectorInstances to Functions
• Unlike arrays, objects of vector andstring types are passed by value to functions.– Thus a copy is made of the arguments to the function
call, and changes made to the formal parameter will NOT affect the argument value.
• Pass string and vector objects by reference to allow the function to alter the argument.
• Pass string and vector objects by const reference to avoid copying potentially large datasets.
Copyright © 2012 Pearson Education, Inc.
Standard Template Library Algorithms
• Classes defined in the C++ STL are supported by a collection of top-level functions.– Defined in <algorithm>– Algorithms include search, sort,
random_shuffle, copy, random_sample, partition, transform, and others.
• See http://www.sgi.com/tech/stl/table_of_contents.html for STL documentation.
Copyright © 2012 Pearson Education, Inc.
Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
Notation indicates that every CardDeck
has 52 Cards