Download presentation
Presentation is loading. Please wait.
1
One Dimensional Arrays
Copyright © 2012 Pearson Education, Inc. Chapter 7 One Dimensional Arrays
2
Copyright © 2012 Pearson Education, Inc.
Outline Objectives Arrays Problem Solving Applied: Hurricane Categories Statistical Measurements Problem Solving Applied: Speech Signal Analysis Sorting and Search Algorithms Problem Solving Applied: Tsunami Warning Systems Character Strings The string class The vector class Problem Solving Applied: Calculating Probabilities Copyright © 2012 Pearson Education, Inc.
3
Copyright © 2012 Pearson Education, Inc.
Objectives Develop 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 Copyright © 2012 Pearson Education, Inc.
4
Copyright © 2012 Pearson Education, Inc.
Arrays Copyright © 2012 Pearson Education, Inc.
5
Copyright © 2012 Pearson Education, Inc.
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.
6
Array Definition Syntax
data_type identifier[ [array_size] ] [= initialization_list ]; //array_size must be an integer constant Examples int data[5]; //allocates consecutive memory for 5 integer values char vowels[5] = {‘a', ‘e', ‘i', ‘o', ‘u'}; //allocates and initializes double t[100] = {0.0}; //allocates and initialized all values to 0.0 Valid References cout << vowels[0]; cout << t[2]; Invalid References cout << vowel[5]; //invalid offset. cout << t[-1]; //invalid offset Copyright © 2012 Pearson Education, Inc.
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' ansKey true true false true false false word 'H' 'e' 'l' 'l' 'o' '\0'
8
Accessing Array Elements
Offsets are used to access individual elements of an array. General format: array_identifier[offset] Example for (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.
9
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.
10
Copyright © 2012 Pearson Education, Inc.
Operator Precedence Precedence Operator Associativity 1 () [] Innermost First 2 Unary operators: ! (type) Right to left 3 * / % Left to right 4 + - 5 < <= > => 6 == != 7 && 8 || 9 ? : 10 = += -= *= /= %= 11 , Copyright © 2012 Pearson Education, Inc.
11
Copyright © 2012 Pearson Education, Inc.
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.
12
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.
13
Copyright © 2012 Pearson Education, Inc.
Example // This function inputs values into an array until EOF // or array limit reached void ReadArray(double a[], int& count, istream& in) { double temp; count = 0; in >> temp; while ( (count < MAXSIZE) && !in.eof() ) { a[count] = temp; ++count; } Copyright © 2012 Pearson Education, Inc.
14
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.
15
Problem Solving Applied: Hurricane Categories
Copyright © 2012 Pearson Education, Inc.
16
Expected Property Damage
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. Category Wind Speed (mph) Storm Surge (feet) Expected Property Damage 1 74-95 4-5 Minimal 2 96-110 6-8 Moderate 3 9-12 Extensive 4 13-18 Extreme 5 155+ 18+ Catastrophic Copyright © 2012 Pearson Education, Inc.
17
Problem Solving Applied: Hurricane Categories
Copyright © 2012 Pearson Education, Inc.
18
Problem Solving Applied: Hurricane Categories
Copyright © 2012 Pearson Education, Inc.
19
Problem Solving Applied: Hurricane Categories
Copyright © 2012 Pearson Education, Inc.
20
Statistical Measurements
Copyright © 2012 Pearson Education, Inc.
21
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.
22
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.
23
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.
24
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.
25
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 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. Copyright © 2012 Pearson Education, Inc.
26
Copyright © 2012 Pearson Education, Inc.
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 //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 Copyright © 2012 Pearson Education, Inc.
27
Copyright © 2012 Pearson Education, Inc.
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 //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 Copyright © 2012 Pearson Education, Inc.
28
Copyright © 2012 Pearson Education, Inc.
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 //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 Copyright © 2012 Pearson Education, Inc.
29
Copyright © 2012 Pearson Education, Inc.
Computing the Mean //This function computes the mean of a dataset //contained in an array. // Mean = Sum(all array elements)/size double 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.
30
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.
31
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.
32
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.
33
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.
34
Problem Solving Applied: Speech Signal Analysis
Copyright © 2012 Pearson Education, Inc.
35
Problem Solving Applied: Speech Signal Analysis
Copyright © 2012 Pearson Education, Inc.
36
Problem Solving Applied: Speech Signal Analysis
Copyright © 2012 Pearson Education, Inc.
37
Problem Solving Applied: Speech Signal Analysis
Copyright © 2012 Pearson Education, Inc.
38
Sorting and Searching Algorithms
Copyright © 2012 Pearson Education, Inc.
39
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.
40
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.
41
Copyright © 2012 Pearson Education, Inc.
Selection Sort //This function sorts the array with n elements //into ascending order using selection sort void 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.
42
Copyright © 2012 Pearson Education, Inc.
Searching Algorithms Search algorithms are grouped according 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.
43
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.
44
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: top and bottom cross over (search failed). Copyright © 2012 Pearson Education, Inc.
45
Example of Binary Search for 48
5 11 14 22 28 37 43 56 59 70 arr[top] arr[mid] arr[bot] 37 43 56 59 70 mid is 7 arr[top] arr[mid] arr[bot] mid is 5 43 37 arr[top] arr[bot] mid is 6 43 arr[6] 43 arr[bot] arr[top] Copyright © 2012 Pearson Education, Inc.
46
Problem Solving Applied: Tsunami Warning Systems
Copyright © 2012 Pearson Education, Inc.
47
Problem Solving Applied: Tsunami Warning Systems
Copyright © 2012 Pearson Education, Inc.
48
Problem Solving Applied: Tsunami Warning Systems
Copyright © 2012 Pearson Education, Inc.
49
Problem Solving Applied: Tsunami Warning Systems
Copyright © 2012 Pearson Education, Inc.
50
Copyright © 2012 Pearson Education, Inc.
Character Strings Copyright © 2012 Pearson Education, Inc.
51
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.
52
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.
53
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.
54
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.
55
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.
56
Copyright © 2012 Pearson Education, Inc.
The string Class Copyright © 2012 Pearson Education, Inc.
57
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.
58
Common Methods of the string Class
size( ) empty( ) substr (int start, int len) c_str() Copyright © 2012 Pearson Education, Inc.
59
Operators Overloaded for the string Class
relational operators < > == <= >= concatenation + += assignment = Copyright © 2012 Pearson Education, Inc.
60
Copyright © 2012 Pearson Education, Inc.
String Class Example #include <iostream> #include <string> //string class uses 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.
61
Copyright © 2012 Pearson Education, Inc.
The vector Class Copyright © 2012 Pearson Education, Inc.
62
Copyright © 2012 Pearson Education, Inc.
The vector Class Predefined type included in the Standard 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.
63
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.
64
Common Methods of the vector Class
back() begin() capacity() empty( ) end() erase() insert() pop_back() pop_front() resize( ) size( ) Copyright © 2012 Pearson Education, Inc.
65
Passing string and vector Instances to Functions
Unlike arrays, objects of vector and string 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.
66
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 for STL documentation. Copyright © 2012 Pearson Education, Inc.
67
Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
68
Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
69
Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
70
Problem Solving Applied: Calculating Probabilities
Notation indicates that every CardDeck has 52 Cards Copyright © 2012 Pearson Education, Inc.
71
Problem Solving Applied: Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
72
Flowchart for Calculating Probabilities
Copyright © 2012 Pearson Education, Inc.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.