Recursion
1. Consider the following function:
void recursePrint(int n)
{
if (n != 0) // Line 1
{
cout << "Hip\n"; //Line 2
recursePrint(n - 1); // 3
}
else
cout << "Horray!"; // 4
}
a. What is the base case?
b. What is the recursive case?
c. How many times is recursePrint called if the line:
recursePrint(4);
is in the main program?
2. Consider the following recursive function (Chapter 17, #9, modified)
void recFun(int x)
{
if (x > 10)
{
recFun(x / 10);
cout << x % 10;
}
else
cout << x;
}
a. What is printed by the call: recFun(268);
b. How can the code be modified so that when a number is input, its digits are printed on separate lines?
c. How can the code be modified so that the sum of all digits is printed?
3. Use a recursive function findRecurse that returns true if an element is an array and false otherwise:
base case: The element is equal to the first item in the array; returns true. Alternatively there are no elements left in the array, returns false.
recursive case: The element is not equal to the first item in the array. This means that we have to search the rest of the array for the item.