Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

This is how to do it :

public static void main(String[] args) {
    recursiveAlphabet('a');
    recursiveAlphabetReverse('z');
}

public static void recursiveAlphabet(char current) {
    System.out.println(current);
    if (current != 'z') {
        recursiveAlphabet((char) (current + 1));
    }
}

public static void recursiveAlphabetReverse(char current) {
    System.out.println(current);
    if (current != 'a') {
        recursiveAlphabetReverse((char) (current - 1));
    }
}

If you need, you can have both in one method, which looks like this :

public static void main(String[] args) {
    resursiveBothSide('a', true);
}

public static void resursiveBothSide(char current, boolean forward) {
    System.out.println(current);
    if ((current == 'z') && (forward)) {
        forward = false;
    }
    if (forward) {
        resursiveBothSide((char) (current + 1), forward);
    } else {
        if (current != 'a') {
            resursiveBothSide((char) (current - 1), forward);
        }
    }
}

To print an alphabet in forward direction: print the first character of the alphabet, then print an alphabet without the first character.

To print it in reverse, just reverse the order of those two: print an alphabet without the first character, then print the first character.

Do below as simple just remove your if condition:-

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);

Here with simple, single method and without - :

void printrec(char c) {
    if (c > 'z') return;
    System.out.print(c);
    printrec((char) (c+1));
    System.out.print(c);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top