CSCI 159 Quiz 2 Sample Solutions Monday lab
Question 1 [7 marks]
The C++ function below uses a while loop to achieve its repetition. Rewrite the function
so that it uses recursion instead (no loops permitted).
The behaviour from a user perspective must be as close to the original as possible.
// displays the integer values from high down to low (inclusive)
// with a "Done" message at the end
void dispVals(int low, int high)
{
while (low <= high) {
cout << high << endl;
high--;
}
cout << "Done!" << endl;
}
Sample solution
void dispVals(int low, int high)
{
if (low < = high) {
cout << high << endl; // get current (highest) value first
dispVals(low, high-1); // then recurse on lower values
} else {
cout << "Done!" << endl; // must be in else to ensure it only happens in last call
}
}
|
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 a loop to achieve the
repetition (no recursion permitted).
// the function prompts the user to enter a number greater than 1,
// performs appropriate error checking and gets the user
// to try again until a valid response is provided,
// and returns the eventual valid response
float getAbove10();
Sample solution
float getAbove1()
{
float num;
bool isOK;
do {
isOK = false;
cout << "Enter a number greater than or equal to 1" << endl;
cin >> num;
if (cin.fail()) {
cin.clear();
cin.ignore(80,'\n');
cerr << "Your input must be a number, try again" << endl;
} else if (num <= 1) {
cerr << "The value must be > 1, try again" << endl;
} else {
isOK = true;
}
} while (!isOK);
return num;
}
|
Question 3 [6 marks]
Assuming the getANumber function correctly gets and returns a number from
the user:
(i) Explain the conditions under which the code segment below
results in an 'infinite loop' and suggest a simple fix.
(ii) Explain the conditions under which the body of the loop
might never execute.
double num1, num2;
num1 = getANumber();
num2 = getANumber();
while (num1 < num2) {
cout << num1 << endl;
num1 = num1 * 2;
}
cout << "Done!" << endl;
Sample solution
(i) If num1 < = 0 and num2 > num1 then we can double num1 as often
as we like and it'll still be < num2 (at least until it exceeds
the biggest negative number a double can hold).
One possible fix that doesn't alter the functionality for any other
cases is to expand the while loop test case to something like
while ((num1 > 0) && (num1 < num2)) {
(ii) The loop body never runs if num1 >= num2 from the very start.
|