Reputation: 41
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.
Upvotes: 0
Views: 8405
Reputation: 13
import java.util.*;
import java.io.*;
public class Main
{
static void print(char n){
if(n=='z'){
System.out.print(n);
return;
}
System.out.print(n+" ");
print((char)(n+1)) ;
}
public static void main(String [] arg){
print('a');
}
}
/*
Output: a b c d e f g h i j k l m n o p q r s t u v w x y z
*/
Upvotes: 0
Reputation: 36349
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);
}
Upvotes: 0
Reputation: 4185
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
Upvotes: 0
Reputation: 15025
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);
Upvotes: 0
Reputation: 23049
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);
}
}
}
Upvotes: 1
Reputation: 490478
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.
Upvotes: 0