RECURSIVE ALGORITHM TO PRINT ALL THE CHARACTERS IN A STRING IN REVERSE - ONE CHARACTER PER LINE
If the string is empty then nothing is printed.This becomes the base case.
For the recursive case, consider the string which will have two parts: first character and the remaining string.
We consider the substring except the first character and pass it as an argument to our print method. This method further breaks the input into the first character and the remaining portion of the string. The second part is thus recursively broken down until only one character is left and which gets printed.
Consider the string "WARDEN"
WARDEN = W + ARDEN
ARDEN = A + RDEN
RDEN = R + DEN
DEN = D + EN
EN = E + N
N = N (PRINT)
THEN PRINT(E)
AND SO ON.
RecursivePrintString(X1X2....Xn)
1 If X is empty then print nothing
2 else
3 RecursivePrintString(X2...Xn)
JAVA IMPLEMENTATION
import java.util.Scanner;
/**
* Created by Ganesh.r.hegde on 15-Feb-18.
*/
public class RecursivePrintChars {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string whose characters are required to be printed in reverse : ");
String text= scan.nextLine();
//display result to the user
System.out.println("The characters of string "+text+" in reverse is displayed below :");
//method call
strPrintReverse(text);
}
/** Recursive method strPrintReverse
post: The argument string is displayed in reverse,
one character per line.
@param str The string
*/
public static void strPrintReverse(String str) {
if (str == null || str.isEmpty()) {
return;
} else {
strPrintReverse(str.substring(1));
System.out.println(str.charAt(0));
}
}
}