Section 1.12 Homework 12 -- Recursion
Exercises Exercises
2.
3.
When a new function call is made, which of the following is NOT saved as part of the activation record (a.k.a., stack frame) for that function when it is added to the top of the runtime stack?
- the number of times the function has been called
- variables defined locally in the function
- function parameters and their values
- location in the calling program to return to when the current function ends
4.
5.
6.
Write a recursive function,
rec_is_pal, that takes a string and returns true if the string is a palindrome; otherwise, returns false. Each recursive call should be dealing with the question for a string with a smaller size.
For example:
| Test | Result |
|---|---|
if (rec_is_pal("racecar")) {
cout << "PALINDROME";
else {
cout << "not a palindrome";
}
|
PALINDROME |
if (rec_is_pal("racebar")) {
cout << "PALINDROME";
else {
cout << "not a palindrome";
}
|
not a palindrome |
if (rec_is_pal("abba")) {
cout << "PALINDROME";
else {
cout << "not a palindrome";
}
|
PALINDROME |
if (rec_is_pal("ABCA")) {
cout << "PALINDROME";
else {
cout << "not a palindrome";
}
|
not a palindrome |
7.
Write a recursive function,
rec_choose, that takes two integers, `n` and `k`, and returns the value of n choose k.
The value [n choose k] represents the number of ways of picking k distinct objects out of a set of n distinct objects. For example, suppose we have four people; Alice (A), Balthazar (B), Charlize (C) and Douglass (D). How many ways could you pick a pair of them? Six: AB, AC, AD, BC, BD and CD. That is 4 choose 2 = 6.
The standard definition of n choose k involves factorials. However, there is also a recursive definition (Pascalβs Identity):
n choose k = (n-1 choose k-1) + (n-1 choose k), for 0 < k < n
The first base case is when k is out of range (k < 0 or k > n). Itβs impossible to choose k items in this case, so the answer is 0.
The second base case is when k is 0. There is only one way to choose nothing, so the answer is 1.
The third base case is when k equals n. There is only one way to choose n things from n things, so the answer is 1.
For the math behind this, see http://mathworld.wolfram.com/BinomialCoefficient.html.
For example:
You have attempted of activities on this page.
