Name _____________________ Section time _______________ Section instructor ___________________
In this lab, you will gain experience with writing recursive functions. Remember that creating/understanding a recursive function involves four points.
0, 1, 2, ...
,
the base case is 0
, or 0
and 1
, usually.
For a function that works on a String
, the base case is the ""
or a String
of length 0 or 1, usually.String s
, the solution should be describable in terms of the same
problem on a substring of s
. In writing/understanding a recursive call, understand it in terms of the specification of the function being called.
On your computer, create a new folder. In DrJava, start a new class named Rec
(for Recursion) and make sure that it is saved in the new folder.
Also, start a JUnit test class called RecTester
. As you develop the functions below, create the necessary test cases to
test them and place appropriate assertEquals
procedure calls in RecTester
. Test each function this way before going on to the next one.
Because you are new to recursion, we will help you out by giving you a skeleton with all the methods headers and method specifications filled in for you —in file Rec.java on the course website. But please remember that you couldn't write these methods without a complete specification! When you design your own methods, write the specifications first. You may not finish these during the lab. If not, finish them at home and show the file to your TA the next week.
1. Count the number of times a character appears in a String.
2. Produce a copy of a string with each character duplicated.
3. Produce a copy of String s with the first occurrence of character c removed (if present).
4. Produce a copy of String s with all occurrences of character c removed.
5. Produce the reverse of a String. For example, for the String "abcd", the result is "dcba". We give hints.
6. Compute Fibonnaci number n. The Fibonnaci numbers are 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Fibonnaci number 0 is 0, Fibonnaci number 1 is 1, Fibonnaci number 6 is 13. Each number (except the first two) is the sum of the two previous ones.
7. Computer b to the power c, for c ≥ 0. We give hints.