Chapter 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

1.5.1: Modifying a string parameter: Spaces to hyphens. Run the program, noting correct output. Remove the & and run again, noting the string is not modified, because the string is pass by value and thus the function modifies a copy. When done replace the & Prints: Enter string with spaces: Hello there everyone!!! String with hyphens: Hello-there-everyone!!!

#include <iostream> #include <string> using namespace std; // Function replaces spaces with hyphens void StrSpaceToHyphen(string& modStr) { int i = 0; // Loop index for (i = 0; i < modStr.length(); ++i) { if (modStr.at(i) == ' ') { modStr.at(i) = '-'; } } return; } int main() { string userStr; // Input string from user // Prompt user for input cout << "Enter string with spaces: " << endl; getline(cin, userStr); // Call function to modify user defined string StrSpaceToHyphen(userStr); // Output modified string cout << "String with hyphens: "; cout << userStr << endl; return 0; }

Figure 1.5.1: Modifying a string parameter, which should be pass by reference. The following function modifies a string by replacing spaces with hyphens. Prints: Enter string with spaces: Hello there everyone. String with hyphens: Hello-there-everyone. ... Enter string with spaces: Good bye now !!! String with hyphens: Good-bye--now---!!

#include <iostream> #include <string> using namespace std; // Function replaces spaces with hyphens void StrSpaceToHyphen(string& modStr) { int i = 0; // Loop index for (i = 0; i < modStr.length(); ++i) { if (modStr.at(i) == ' ') { modStr.at(i) = '-'; } } return; } int main() { string userStr; // Input string from user // Prompt user for input cout << "Enter string with spaces: " << endl; getline(cin, userStr); // Call function to modify user defined string StrSpaceToHyphen(userStr); // Output modified string cout << "String with hyphens: "; cout << userStr << endl; return 0; } // notes: string serves as function input and output //The string parameter must be pass by reference, achieved using & (yellow highlighted), so that the function modifies the original string argument (userStr) and not a copy.

Figure 1.5.2: Normal and constant pass by reference vector parameters in a vector reversal program. Prints: Enter 8 values... Value: 10 Value: 20 Value: 30 Value: 40 Value: 50 Value: 60 Value: 70 Value: 80 New values: 80 70 60 50 40 30 20 10

#include <iostream> #include <vector> using namespace std; void ReverseVals(vector<int>& vctrVals) { int i = 0; // Loop index int tmpVal = 0; // Temp variable for swapping for (i = 0; i < (vctrVals.size() / 2); ++i) { tmpVal = vctrVals.at(i); // These statements swap vctrVals.at(i) = vctrVals.at(vctrVals.size() - 1 - i); vctrVals.at(vctrVals.size() - 1 - i) = tmpVal; } return; } void PrintVals(const vector<int>& vctrVals) { int i = 0; // Loop index // Print updated vector cout << endl << "New values: "; for (i = 0; i < vctrVals.size(); ++i) { cout << " " << vctrVals.at(i); } cout << endl; return; } int main() { const int NUM_VALUES = 8; // Vector size vector<int> userValues(NUM_VALUES); // User values int i = 0; // Loop index // Prompt user to populate vector cout << "Enter " << NUM_VALUES << " values..." << endl; for (i = 0; i < NUM_VALUES; ++i) { cout << "Value: "; cin >> userValues.at(i); } // Call function to reverse vector values ReverseVals(userValues); // Print reversed values PrintVals(userValues); return 0; }

1.4.1: Function pass by reference: Transforming coordinates. Define a function CoordTransform() that transforms its first two input parameters xVal and yVal into two output parameters xValNew and yValNew. The function returns void. The transformation is new = (old + 1) * 2. Ex: If xVal = 3 and yVal = 4, then xValNew is 8 and yValNew is 10. Prints: (3,4) outputs (8,10) (0,0) outputs (2,2)

#include <iostream> using namespace std; /* Your solution goes here */ void CoordTransform (int xVal ,int yVal ,int& xValNew, int& yValNew) { xValNew = (xVal +1) *2; yValNew = (yVal +1) *2; return; } int main() { int xValNew = 0; int yValNew = 0; CoordTransform(3, 4, xValNew, yValNew); cout << "(3, 4) becomes " << "(" << xValNew << ", " << yValNew << ")" << endl; return 0; }

Pass by reference example (1.4.3) Complete the monetary change program. Use the fewest coins (i.e., using maximum larger coins first). Prints: Enter total cents: Quarters: Dimes: Nickels: Pennies:

#include <iostream> using namespace std; // FIXME: Add parameters for dimes, nickels, and pennies. void ComputeChange(int totCents, int& numQuarters, int& numDimes, int& numNickels, int& numPennies) { numQuarters = totCents / 25; numDimes = numQuarters / 10; numNickels = numDimes / 5; numPennies = numNickels % 1; return; } int main() { int userCents = 0; int numQuarters = 0; int numDimes = 0; int numNickels = 0; int numPennies = 0; // FIXME add variables for dimes, nickels, pennies cout << "Enter total cents: " << endl; cin >> userCents; ComputeChange(userCents, numQuarters, numDimes, numNickels, numPennies); cout << "Quarters: " << numQuarters << endl; cout << "Dimes: " << numDimes << endl; cout << "Nickels: " << numNickels << endl; cout << "Pennies: " << numPennies << endl; return 0; }

Reference variable example Prints: Enter an integer: 42 We wrote your integer to usrValInt. usrValInt is: 42. usrValRef refers to usrValInt, and is: 42. We assigned usrValInt with 99. usrValInt is now: 99. usrValRef is now: 99. Note that usrValRef refers to usrValInt, so changed too.

#include <iostream> using namespace std; int main() { int usrValInt = 0; int& usrValRef = usrValInt; // Refers to usrValInt cout << "Enter an integer: "; cin >> usrValInt; cout << "We wrote your integer to usrValInt." << endl; cout << "usrValInt is: " << usrValInt << "." << endl; cout << "usrValRef refers to usrValInt, and is: " << usrValRef << "." << endl; usrValInt = 99; cout << endl << "We assigned usrValInt with 99." << endl; cout << "usrValInt is now: " << usrValInt << "." << endl; cout << "usrValRef is now: " << usrValRef << "." << endl; cout << "Note that usrValRef refers to usrValInt, so changed too." << endl; return 0; }

reference variables examples What is the output? Prints: 1. studentsRef refers to numAStudents, which is 12, so 12 is output. 2. examGrade is incremented to 96. gradeRef refers to examGrade, so examGrade's current value 96 is output. 3. Assigning heightRef with 12.2 assigns the referenced variable treeHeightFt with 12.2. So, 12.2 is output. 4. int& myScore = teamScore myScore is initialized to refer to teamScore. A reference variable must be initialized when declared.

1. int numAStudents = 12; int numBStudents = 5; int& studentsRef = numAStudents; cout << studentsRef; 2. int examGrade = 95; int& gradeRef = examGrade; examGrade = examGrade + 1; cout << gradeRef; 3. double treeHeightFt = 7.1; double& heightRef = treeHeightFt; heightRef = 12.2; cout << treeHeightFt; 4. Declare a reference named myScore and initialize the reference to the int variable teamScore.

constants and pass by reference How should a function's vector parameter ages be defined for the following situations?

1. ages will always be small (fewer than 10 elements) and the function will not modify the vector. constant but not pass by reference: Constant prevents the function from modifying ages. Since ages is small, pass by reference is not used; instead, a copy of ages is made. 2. ages will always be small, and the function will modify the vector. pass by reference but not constant: Pass by reference makes ages modifiable, but constant prevents ages from being modified. 3. ages may be very large, and the function will modify the vector. pass by reference but not constant: Pass by reference makes ages modifiable, but constant prevents ages from being modified. 4. ages may be very large, and the function will not modify the vector. constant and pass by reference: Constant prevents the function from modifying ages. Since ages is large, pass by reference is used to pass the original vector, instead of creating a copy.

Get a user's full name by prompting "Enter full name" and then automatically separating into first and last names.

void GetUserFullName (string& firstName, string& lastName) ...

Convert userMeters into userFeet and userInches (three parameters, in that order), types are doubles. Pass by reference enables the function to "return" the two interrelated values of feet and inches.

void MetersToFeetInches (double userMeters, double& userFeet, double& userInches) { ... }


Set pelajaran terkait

Chapter 10: the New Frontier and the Great Society

View Set

Module 22: Biology, Cognition, and Learning

View Set

Abnormal Psychology Final Chapter 13-16

View Set

Solving Quadratic Equations by Factoring, Set 1

View Set

Chapter 48 Skin Integrity and Wound Care

View Set

Marketing Chapter 12 - Developing New Products

View Set

7C Showing relationship between ideas

View Set

Law Quiz 3 pg. 41-43 & pg. 48-54

View Set