*In Java Please
RECURSION
Objectives
• Learn the basics of recursion – Part II (last week was Part
I)
Submission Guidelines:
You will turn in 2 program files (one for each lab problem)
Tasks
This lab has two parts:
1. Write a recursive method repeatNTimes(String s, int n) that
accepts a String and an
integer as two parameters and returns a string that is concatenated
together n times. (For
example, repeatNTimes ("hello", 3) returns "hellohellohello")
Write a driver program that calls this method from the Main
program.
2. Write a recursive method called isReverse(String s1, String s2)
that accepts two
strings as parameters and returns true if the two strings contain
the same sequence of characters as
each other but in the opposite order and false otherwise.
• The recursive function should ignore capitalization. (For
example, the call of
isReverse("hello", "eLLoH") would return true.)
• The empty string, as well as any one letter string, should be its
own reverse.
Write a driver program that calls this method from the Main
program.
Note: Your program name should match the name of your java / C#
class exactly.
e.g Lab10a.java / Lab10a.cs
Sample Output:
LAB 1:
//A call to recursive function repeatNTimes(“hello”, 5)
hellohellohellohellohello
// A call to recursive function repeatNTimes(“Good morning!”,
3)
Good morning!Good morning!Good morning!
LAB 2:
Page 2 of 2
//Call to recursive function isReverse
("Computer","retupmCo")
false
//Call to recursive function isReverse ("Hello","olleh")
true
Grading:
● 100 %: Attempted lab and submitted fully functioning lab
exercises with complete
headers and clear I/O statements and
● 95 %: Attempted lab and submitted fully functioning lab exercises
but incomplete
headers and/or unclear I/O statements before due date.
● 90%: All but one item are correct
● 80%: At least two more items are correct
● 70%: Program compiles and methods are correct
● 0%: Did not attempt lab or did not submit it before the due
date
1. Java code for repeating the string n times.
import java.util.Scanner;
class StringRepeat{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string:");
String str = in.nextLine();
System.out.print("Enter how many times to be repeated:");
int n = in.nextInt();
//Recursive function calling
System.out.println(repeatNTimes (str,n));
}
//Recursive function definition
public static String repeatNTimes(String s, int n){
if(n==0){
return "";
}
return s+repeat(s,n-1);
}
}
Output Screen
Get Answers For Free
Most questions answered within 1 hours.