RecursionPracticeKey 16KB Feb 23 2015 07:34:01 PM

advertisement
Recursion Practice
Given this function:
int boogie(int x, int y)
{
if(y < 2)
return x;
else
return boogie(x, y-2) + x;
}
Decompose this recursive call (like on page 628) until you
reach an expression you can evaluate:
boogie(5,8)
boogie(5,6) + 5
boogie(5,4) + 5 + 5
boogie(5,2) + 5 + 5 + 5
boogie(5,0) + 5 + 5 + 5 + 5
5
+ 5 + 5 + 5 + 5
Given the recursive definition of greatest common
divisor:
int gcd(int m int n)
{
if(m % n == 0)
return n;
else
return gcd(n, m % n);
}
Trace the call stack that will be produced by this call and
the value that will be returned back down the stack from
the final call:
gcd(9,24)
gcd(24,9)
gcd(9,6)
gcd(6,3)
3
What will the output of these functions be? Trace mentally with n = 5 (unless otherwise specified), then try on
computer
Function void fun(int n) {
void fun2(int n) {
if(n == 1)
if(n == 1)
cout << 1 << " ";
cout << 1 << " ";
else{
else{
cout << n << " ";
fun2(n - 1);
fun(n - 1);
cout << n << " ";
}
}
}
}
Output
54321
12345
Output
void fun3(int n) {
if(n == 1)
cout << 1 << " ";
else{
cout << n << " ";
fun3(n - 1);
cout << n << " ";
}
}
543212345
//try with n = 5 and i = 4
//make sure to print result
int fun4(int n, int i) {
if(i == 1)
return n;
else {
return n + fun4(n, i - 1);
}
}
20
//test with 123
//make sure to print result
int fun5(int n) {
if(n == 0)
return 0;
else {
return (n%10) + fun5(n/10);
}
}
Output
6
Output
//test with "hello there everyone"
//make sure to print result
int fun7(string& s) {
if(s.length() == 0)
return 0;
else {
string shorter = s.substr(1);
if(s[0] == ' ')
return 1 + fun7(shorter);
else
return fun7(shorter);
}
}
2
Challenge Problem:
This one is evil - get some scratch paper and trace the call stack…
Notice that each general case makes two recursive calls.
void evil(int n) {
if(n <= 1)
cout << 1 << endl;
else{
cout << n << " ";
evil(n - 1);
evil(n - 2);
}
}
//no return value, just focus on the output
void fun6(int n) {
cout << n << " ";
if(n == 1)
return;
if(n % 2 == 0) //even
fun6(n/2);
else //odd
fun6(3*n+1);
}
5 16 8 4 2 1
//make sure to print result - test with "there" and
//"apple"
string fun8(string& s) {
if(s.length() == 0)
return string("");
else {
string shorter = s.substr(1);
if(s[0] == 'e')
return fun8(shorter);
else
return s[0] + fun8(shorter);
}
}
there: thr
apple: appl
Download