Search code examples
javaloopsfor-looprecursionalphabet

How to print a through z using a recursive method


Hi new to java here and I need to print the alphabet from a to z and in reverse from z to a. I need to do this using a recursive method.

class Alphabets{


public static void main(String args[]){
  char ch;
  for( ch = 'a' ; ch <= 'z' ; ch++ )
    System.out.print(ch);
  System.out.println();
  for( ch = 'z' ; ch >= 'a' ; ch--)
     System.out.print(ch);

  if (ch <= 'a') ch = ch--;
    else if(ch >='a') ch = ch++;
    System.out.print(ch);

 }
}

My output for the two for loops seems to work just fine but I am completely lost on the recursive method.


Solution

  • public static void printCharRecur(char ch) {
     if(ch=='z') System.out.print("z z");
     else {
      System.out.print(ch);
      printCharRecur((char) (ch+1));
      System.out.print(ch);
     }
    }
    

    Call printCharRecur('a') from main