java Considering the following code segment, answer the multiple choice questions.
public String foo(String input) {
String str = input.toLowerCase();
return bar(str);
}
private String bar(String s) {
if (s.length() <= 1) {return "";}
else if (s.length() % 2 == 0) {return "*" + bar(s.substring(2, s.length()));}
else if (s.length() % 2 == 1) {return "*" + bar(s+"n");}
else {return "";}
}
Which line(s) indicate the name of the helper method? Which line(s) contains recursive call(s)? How many * are in the return String when we call bar("Dave")?
Ans
bar is helper function of foo. call of bar in foo function indicate that bar is helper of foo.
Below statement in foo indicate helper
return bar(str);
.
.
Recursive call occurs if function call itself.
in bar function there are two recursive calls based on condition in else if.
bar(s.substring(2, s.length())
bar(s+"n");
are recursive calls
.
.
.
bar("Dave)
length of string = 4
in if else ladder
s.length%2 turns out true that concatenate * and call recursively bar("ve") (substring returns string from index 2 to last) and return
length of ve = 2
s.length%2 turns true concatenate * and recursive call to bar("")
for bar("") length =0
so s.length<=1 turns true and return "" to previous 2nd call.
2nd call return * to 1st call
1st call return **
.
Hence two * are returned on call bar("Dave")
.
.
.If any doubt ask in the comments.
Get Answers For Free
Most questions answered within 1 hours.