Consider the recursive function pingPong described below.
static String pingPong(int x) { if (x % 2 == 0 && x % 3 == 0) return "ping-pong"; else if (x % 2 == 0) return "ping," + pingPong(x - 1); else if (x % 3 == 0) return "pong," + pingPong(x - 1); else return "?," + pingPong(x - 1); }
a) what's the base-case of pingPong?
b) what's the result of pingPong(10)?
a) what's the base-case of pingPong?
In the given function, the base case is:
if (x % 2 == 0 && x % 3 == 0) return "ping-pong";
It is called the base case because it terminates the recursion by not making any further recursive calls and provides a suitable output.
b) what's the result of pingPong(10)?
The output of pingPong(10) will be:
ping,pong,ping,?,ping-pong
The code with corresponding output is as follows:
import java.util.*;
public class ping{
public static String pingPong(int x) {
if (x % 2 == 0 && x % 3 == 0)
return "ping-pong";
else if (x % 2 == 0)
return "ping," + pingPong(x - 1);
else if (x % 3 == 0)
return "pong," + pingPong(x - 1);
else
return "?," + pingPong(x - 1);
}
public static void main(String []args){
String s;
s=pingPong(10);
System.out.println(s);
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.