CS210 Lab: Recursion Postlab Answers
Postlab Answers:
Use the following function to answer Questions 1 and 2.
int Puzzle (int base, int limit)
{
if (base > limit)
return -1;
else
if (base == limit)
return 1;
else
return base* Puzzle(base+1, limit);
}
- Identify the following:
- the base case(s) of the function Puzzle
- if
(base > limit), return -1;
- else if
(base == limit), return 1;
- the general (recursive) case(s) of the function
Puzzle
if (base < limit),
return base* Puzzle(base+1, limit);
- Show what would be written by the following calls to the recursive
function Puzzle
- cout << Puzzle(20,5);
-1
because it hits the base case:
if (base > limit), return -1
- cout << Puzzle(3,6);
60
because it results in something like the following:
3 * Puzzle(4,6);
3 * 4 * Puzzle(5,6);
3 * 4 * 5 * Puzzle(6,6);
3 * 4 * 5 * 1
- cout << Puzzle(8,8);
1
because it hits the base case:
else if (base == limit), return 1;
Back to Exercise click
here
Back to Recursion Lab click
here
Copyright: Department of Computer Science, University of Regina.