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);
}
  1. Identify the following:
    1. the base case(s) of the function Puzzle
      1. if (base > limit), return -1;
      2. else if (base == limit), return 1;

    2. the general (recursive) case(s) of the function Puzzle
          if (base < limit), return base* Puzzle(base+1, limit);

  2. Show what would be written by the following calls to the recursive function Puzzle
    1. cout << Puzzle(20,5);
          -1
      because it hits the base case:
      if (base > limit), return -1

    2. 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

    3. 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

CS Dept Home Page
CS Dept Class Files
CS210 Class Files

Copyright: Department of Computer Science, University of Regina.