Skip to main content

Section 21.12 Exercises

Checkpoint 21.12.1.

Implement the recursive function: int power(int x, int p)
The returned value should be x to the p power. You don’t have to worry about negative exponents. Note that the function header is there, you just need to fill in the body.
Hint 1.
What is an easy obvious power to calculate for any value x? That is a base case.
Hint 2.
Say you were told to calculate 5 to the 10th power and knew you could ask me what the value of 5 to the 9th power was. How could you get your answer?

Checkpoint 21.12.2.

Write a function int investmentLength(double money, double goal, double interestRate) that returns the time it will take to reach the given goal if you start with the given amount of money and invest at the specified interest rate. (Interest rate will be a %, divide by 100.0 before using).
Hint 1.
Your base case should return 0 - indicating you don’t need to invest for any years because you’ve met your goal
Hint 2.
The general case represents one more year of your money having been invested. It should return one year plus the result of the recursive call with updated parameters.
Hint 3.
If you leave the money invested until next year, what would the new amount of money be? Would the goal or interest rate change for the recursive call?

Checkpoint 21.12.3.

Implement a recursive function to turn an integer into a string of binary digits (1s and 0s) string makeBinary(int n)
Use the divide by 2 method to convert decimal to binary (you can refer to Welcome to CS for how the algorithm works).
The logic for converting 13 to binary (1101):
Number /2 Quotient /2 Remainder Result Comment
13 6 1 "1"
Add 1 to answer, continue working with 6
6 3 0 "01"
Add 0 to answer, continue working with 3
3 1 1 "101"
Add 1 to answer, continue working with 1
1 0 1 "1101"
Add 1 to answer, continue working with 0
0 0 0 "1101" Once we reach 0, stop.

Checkpoint 21.12.4.

Implement the function: double series(int steps)
This function should return the sum of the first steps number of terms from the series 1 + 1/2 + 1/4 + 1/8 + 1/16....
For example:

Checkpoint 21.12.5.

Implement the function int letterCount(const string& s, char a). It should return the number of times char a appears in s.
If you want to avoid making substrings of s, you can create a recursive helper that the provided letterCount calls.

Checkpoint 21.12.6.

Write a function int numLegs(const vector<char>& animals, int curPosition = 0). The vector will consist only of the chars ’c’ and ’d’ representing "cow" or "duck". The function should calculate the total number of legs those animals have (assume no mutations or industrial accidents... a cow has 4 and a duck has 2).
Use the changing index strategy.
Hint.
curPositioncurPosition.size()

Checkpoint 21.12.7.

Implement the function int getMax(const vector<int>&, int curIndex = 0). It should return the largest int in the vector.
Hint.
.size() - 1
You have attempted of activities on this page.