CSCI 159 Quiz 2 (F25N02) Monday lab
The quiz is closed book, closed notes, no electronics permitted, and to be completed as a
strictly individual exercise. You are permitted one double-sided 8.5" x 11" sheet of notes.
The quiz is worth a total of 20 marks. Attempt all three questions, answering directly on the exam paper.
Note that when a code segment is requested you are only expected to put the requested lines of code,
not the rest of a larger program it would be part of. When a complete program is requested, on
the other hand, you should provide the entire program (#includes, int main, etc).
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;
}
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();
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;