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

Java netbeans (recursion) 02- Write a recursive Java method that takes a charact

ID: 3729626 • Letter: J

Question

Java netbeans (recursion)
02- Write a recursive Java method that takes a character string s and outputs its reverse. For example, the reverse of 'pots&pans' would be 'snap&stop'. Test your method. Java netbeans (recursion)
02- Write a recursive Java method that takes a character string s and outputs its reverse. For example, the reverse of 'pots&pans' would be 'snap&stop'. Test your method.
02- Write a recursive Java method that takes a character string s and outputs its reverse. For example, the reverse of 'pots&pans' would be 'snap&stop'. Test your method.

Explanation / Answer

The Algorithm :-

string reverse(string s){

    if (s==null or s.length()==1){

        return s;

    }

    return reverse(s[1..n])+s[0]

}

The base condition is

if(s==null or length of s =1) in both of the cases we return s itself.

Otherwise

return substring from 1 to length of string + character at index[0]

Executable Code :-

package stringreverse;

/**
*
* @author Anonymous
*/
public class Stringreverse {

    /**
     * @paramargs the command line arguments
     */
    public static String reverseString(String s){
        if(s==null || s.length()==1){
            return s;
        }
        return reverseString(s.substring(1))+s.charAt(0);
    }
    public static void main(String[] args){
        String s="cheggIndia";
        s=reverseString(s);
        System.out.println(s);
        // TODO code application logic here
    }
  
}


Sample Test Case :-

say s="cheggIndia"

reverseString("cheggIndia")

(reverseString("heggIndia")+'c')

((reverseString("eggIndia")+'h')+'c')

(((reverseString("ggIndia")+'e')+'h')+'c')

((((reverseString("gIndia")+'g')+'e')+'h')+'c')

(((((reverseString("India")+'g')+'g')+'e')+'h')+'c')

((((((reverseString("ndia")+'I')+'g')+'g')+'e')+'h')+'c')

(((((((reverseString("dia")+'n')+'I')+'g')+'g')+'e')+'h')+'c')

((((((((reverseString("ia")+'d')+'n')+'I')+'g')+'g')+'e')+'h')+'c')

(((((((((reverseString("a")+'i')+'d')+'n')+'I')+'g')+'g')+'e')+'h')+'c')

reverseString("a") return a as length("a")=1

Now The String Becomes 'aidnIggehc" which is the required answer.

Please give Thums up(really helpful) if you find the answers useful.

Thanks

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote