Print a string in reverse using recursion
Here's my code for printing a string in reverse. It works perfectly.
I printed out the string normal and not in reverse no problem. I then just switched the else statement around and it worked. Great huh? But I have no idea how it prints the letter o first then the rest.
Could someone explain it to me?
Much appreciated.
Code Java:
static void printReverse(String s){
if(s==null || s.equals("")){
return;
}
else{
printReverse(s.substring(1)); // print in reverse
System.out.println(s.charAt(0));
// print normal char per line
// System.out.println(s.charAt(0));
// printReverse(s.substring(1));
}
}
public static void main(String[] args) {
printReverse("hello");
}
/*
output is -
o
l
l
e
h
*/
Re: Print a string in reverse using recursion
Try debugging the code by adding lots of printlns that show execution flow and what the args arg that are passed.
Re: Print a string in reverse using recursion
Code java:
System.out.println(s.charAt(0));
The problem is right here. You're printing it wrong.
Re: Print a string in reverse using recursion
It's doing exactly what the question asks. What would be an alternative print?
I know the way a substring works, with printing the rest of a string after the index number but how does the letter o come out first in the recursion?
Re: Print a string in reverse using recursion
Quote:
how it prints the letter o first then the rest.
When is the println statement executed? Manually work through the code (or add some println statements) to trace the order of the execution of the statements in the program.
Re: Print a string in reverse using recursion