CSCI 159 Quiz 2 Sample Solutions Wednesday lab
Question 1 [7 marks]
The C++ function below uses recursion to achieve its repetition. Rewrite the function
so that it uses a loop instead (your choice of which type of loop).
Your solution cannot include any recursion, and the behaviour from a user perspective must
be as close to the original as possible.
// displays the integer values low to high (inclusive)
// with a "Done" message at the end
void dispVals(int low, int high)
{
if (low > high) {
cout << "Done!" << endl;
} else {
cout << low << endl;
dispVals(low+1, high);
}
}
Sample solution
void dispVals(int low, int high)
{
// prints values low to high then Done!
for (int i = low; i < = high; i++) {
cout << i << endl;
}
cout << "Done!" << endl;
}
|
Question 2 [7 marks]
Below is a prototype for function getNegative and comments describing its desired behaviour.
Implement (write the code for) the function, using recursion to achieve the
repetition (no loops permitted).
// the function prompts the user to enter a negative number,
// performs appropriate error checking and gets the user
// to try again until a valid response is provided,
// and returns the eventual valid response
double getNegative();
Sample solution
double getNegative()
{
double num;
cout << "Enter a negative number" << endl;
cin >> num;
if (cin.fail()) {
cin.clear();
cin.ignore(80,'\n');
cerr << "That was not a number, try again" << endl;
num = getNegative(); // or return getNegative();
} else if (num >= 0) {
cerr << "That was not negative, try again" << endl;
num = getNegative(); // or return getNegative();
}
return num;
}
|
Question 3 [6 marks]
Explain the conditions under which the code segment below
results in an 'infinite loop' and provide a simple correction to the loop.
int userVal = 0;
cout << "Please enter an integer greater than 10: ";
cin >> userVal;
while (cin.fail() || (userVal <= 10)) {
if (cin.fail()) {
cerr << "That was not an integer, please try again" << endl;
cin.clear();
cin.ignore(80, '\n');
} else if (userVal <= 10) {
cerr << "That value was too small, please try again" << endl;
} else {
cout << "Thank you for value " << userVal << endl;
}
}
Sample solution
If the user enters too small a number then the loop can never end
because, inside the loop, it never actually tries to cin another value,
it just keeps testing the original value over and over and over.
A fix would be to add
cin >> userVal;
after the cin.ignore and after the cerr in the too-small case
|