CS113 Lab 9: Recursion excursion
Due Friday, May 7, before midnight
Goals
-
Practice writing recursive functions
Recursive functions
In the file, Recursion.java
, write each of the following functions
recursively. You are given basecode containing
functions stubs along with a main
for testing. You can download the
basecode here or use the file in Dropbox.
You must not modify the function parameters and return types for the given functions! |
-
Function
reven(int n)
should recursively sum the even numbers starting at 2 and ending at n. For example,reven(10)
should return 2+4+6+8+10 = 30. -
Function
rrevStr(String word)
should return the reverse of a given string. For example: the reverse of"hello"
is"olleh"
. -
Function
rblastoff(int n)`should count down (print one number per line) from the given start number to 1, then print "blastoff!". For example, `rblastoff(10)
should count down from 10 to 1, then print "blastoff!". -
Function (
rgetMod()
) asks the user to enter an integer that is divisible by 3. Assume the user will enter an integer. If the given integer is not divisible by 3 (Hint: use%
to check), the function should recursively ask the user for another integer. This function should return the valid integer. Below is console output from runningrgetMod
.Enter a number: 4 Not divisible by 3! Enter a number: 6
rgetMod
should return the user’s number! -
Function (
rxerox(String phrase,int n)
) should generate and return a String containingn
copies of the item. For example,rxerox("paper", 4)
should return"paperpaperpaperpaper"
, andrxerox("2", 10)
should return"2222222222"
. -
Function
rraise(int n, int m)
returnsn
raised to the mth power. For example, callingrraise(6,2)
returns 36. -
Function
risPalindrome(String text)
returnstrue
if given text is a palindrome (same forwards and backwards) andfalse
otherwise. For example,risPalindrome("HANNAH")
should returntrue
. -
Function
rcount(char x,String S)
returns how many timesx
is in the StringS
. For example,rcount("a", "aardvark")
should return 3.
Testing your functions
You are given test code in main
. Functions that return a value are tested using the
test
function. This function throws an exception if the function returns an incorrect value.
For example, suppose there is a bug in our function rrevStr
, running gives this error
java.lang.Exception: Test Failed: yolleh != olleh
at Recursion.test(Recursion.java:118)
at Recursion.main(Recursion.java:133)
The above error shows us that our function returned "yolleh" but should have returned the value "olleh". We can also see that the function we need to fix is called on line 133.
We encourage you to add your own tests!
What to hand-in
-
The program,
Recursion.java
-
Make sure your programs have a header containing your name, date, and description.
-
No writeup is necessary for this assignment
How to hand-in
-
Copy your files to your dropbox, into the folder called
A09
.