How to print text diagonally from left to right recursively in Java

1 Answer

0 votes
public class DiagonalPrinter {

    public static void main(String[] args) {
        String text = "HELLO WORLD";
        // Start with an empty string for spaces and the full text
        printTextDiagonallyRecursivelyLTR("", text);
    }

    /**
     * Prints text diagonally from left to right using recursion.
     * @param spaces The current indentation (accumulated spaces)
     * @param word   The remaining part of the string to print
     */
    public static void printTextDiagonallyRecursivelyLTR(String spaces, String word) {
        // Base Case: If the word is empty, stop the recursion
        if (word.length() > 0) {
            // Print the current indentation followed by the first character
            System.out.println(spaces + word.charAt(0));

            // Recursive Call: 
            // 1. Add one space to the 'spaces' string
            // 2. Pass the rest of the word (index 1 to the end)
            printTextDiagonallyRecursivelyLTR(spaces + " ", word.substring(1));
        }
    }
}


/*
run:

H
 E
  L
   L
    O
      
      W
       O
        R
         L
          D

*/

 



answered Apr 8 by avibootz

Related questions

...