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

import java.util.Scanner; public class ReverseString { static String reverse(Str

ID: 3595406 • Letter: I

Question

import java.util.Scanner;

public class ReverseString

{

  static String reverse(String s)

  {

    if (s.equals(""))

      return "";

    else

      return s.charAt(s.length() - 1)

             + reverse(s.substring(0, s.length() - 1));     

  }

  public static void main(String[] args)

  {

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter a string > ");

    String hold = scan.next();

    System.out.println(reverse(hold));

  }

}

Show the sequence of method calls to reverse that the application makes if the user inputs "RECURSE".

Explanation / Answer

// Sample recursive calls when input is RECURSE

Enter a string > RECURSE
First call to function reverse(RECURSE)
Recursive call to function reverse with input arguments (0,6)
Recursive call to function reverse with input arguments (0,5)
Recursive call to function reverse with input arguments (0,4)
Recursive call to function reverse with input arguments (0,3)
Recursive call to function reverse with input arguments (0,2)
Recursive call to function reverse with input arguments (0,1)
Recursive call to function reverse with input arguments (0,0)
Base case reached, return ""
ESRUCER