Sale!

CS 161 Lab 5

\$30.00

Category:

Description

Lab 5
Get checked off for up to 3 points of incomplete work from the previous lab within the
first 10 minutes of the lab.
In this lab, you can form a group of 2-3 individuals. You must be checked off together
as a group at the end of the lab. Although you perform tasks as a group, ensure that
you understand the work and ask questions to TAs as needed.
(5 pts) Computation
A liter is 0.264179 gallons. Write a program that will read in the number of liters of gasoline
consumed by two cars and the number of miles traveled by each car. The program should
output the number of miles per gallon delivered by each car. The program should also
announce which car has the best fuel efficiency (highest number of miles per gallon). The
program should allow the user to repeat this calculation as often as the user wishes.
(5 pts) Pass by Value
● Write a function called swap_sentence(string sen1, string sen2) that takes two string
inputs as parameters and swap them.
○ The prototype for this function is as follows. You need to determine pre conditions
and post-conditions for this function. The preconditions are anything you can say
holds true about the function parameters before the function is called, and the
postconditions are anything you can say holds true about the parameters, after
the function executes.
void swap_sentence(string, string);
● In main function, create two string objects to read the strings from the user, you will
need the <string> library, i.e. #include <string>. Since, a user can enter a single word
or a string with spaces, you will need to use the getline() function to read the
strings/sentences from the user, i.e. getline(cin, s).
● Once you get the two strings from the user, call the function swap_sentence()
● Print the two string objects both in the swap_function() and in the main().
● Example code:
void swap_sentence(string sen1, string sen2){
// swap functionality implemented by you…
cout << “In swap function …” << endl;
cout << “sen1: ” << sen1 << endl;
cout << “sen2: ” << sen2 << endl;
}
int main() {
string sentence1, sentence2;
cout << “Enter sentence 1: ”;
getline (cin, sentence1);
cout << “Enter sentence 2: ”;
getline (cin, sentence2);
swap_sentence(sentence1, sentence2);
cout << “In main function …” << endl;
cout << “sentence1: ” << sentence1 << endl;
cout << “sentence2: ” << sentence2 << endl;
return 0;
}
What did you notice?
Can you find which are formal parameters and which are actual parameters.
Are the sentences swapped in the swap_sentence() function? What about inside main()?
( No implementation in this lab for this part )
Now, how can the swap_sentence() be changed, so it modifies the string parameter directly.
You need to add an & to the string parameter.
void swap_sentence(string &sen1, string &sen2);