Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA Tracing Recursion - PLEASE NO HANDWRITTEN SOLUTIONS THEY ARE TO HARD TO

ID: 3581740 • Letter: I

Question

IN JAVA Tracing Recursion - PLEASE NO HANDWRITTEN SOLUTIONS THEY ARE TO HARD TO READ

String #1

public String s1(String s)

{

   if (s.length() == 0)

      return "";

   return s.substring(0, 1) +

           s1(s.substring(1));

}

What is s1("cat") ?

String #2

public void s2(String s)

{

   if (s.length() > 0)

{

      System.out.print(s.substring(0, 1));

      s2(s.substring(1));

   }

}

What does s2("cat") print?

String #3

public void s3(String s)

{

   if (s.length() > 0)

   {

      s3(s.substring(1));

      System.out.print(s.substring(0, 1));

   }

}

What does s3("cat") print?

Explanation / Answer

public String s1(String s)
{
if (s.length() == 0)
return "";
return s.substring(0, 1) +
s1(s.substring(1));
}
What is s1("cat") ?


Answer:cat
Explanation: as the passed argument "cat" has not length=0,hence it will return s.substring(0, 1) +s1(s.substring(1)); i.e c,a,t equivalent to cat

public void s2(String s)
{
if (s.length() > 0)
{
System.out.print(s.substring(0, 1));
s2(s.substring(1));
}
}

What does s2("cat") print?
Answer: cat
Explanation: as length of cat is greater than 0 hence it will print c,a,t i.e cat


public void s3(String s)
{
if (s.length() > 0)
{
s3(s.substring(1));
System.out.print(s.substring(0, 1));
}
}
What does s3("cat") print?
Answer:tac
Explanation:It will print in reverse order as in the above method we are calling first method recursively then printing it.

Note:In case of any doubt,Please ask would be glad to help you,Thanks!!