0

I want to print all of the letters between two letters using recursion and this is how I did it:

import java.util.*;

public class q24 {

  public static void between(char a, char b) {
    if (a==b) {
      System.out.println(b);
    }
    else {
      System.out.println(a+1);
      between((char)(a+1), b);
    }
  }


  public static void main(String[] args) {
    between('e','l');
  }
}

but it's printing:

102
103
104
105
106
107
108
l

how can I make it print letters?

2 Answers 2

4

When doing arithmetic operations on char (like a + 1), the result value is automatically converted to int.

In order to have the result of the arithmetic operation printed as char, you will have to do an explicit cast:

System.out.println((char) (a+1));

Moreover, I think you have an error in your implementation : the last character (b) will be printed twice - before the last recursion call, and at the recursion bottom. You can fix it like:

public static void between(char a, char b) {
    System.out.println(a);
    if (a < b){
        between((char) (a+1), b);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Thats answered my question :)
0

When you are doing a+1in System.out.println(a+1); it is effectively converting char to int and therefore it is printing ints.

Change it to this :- System.out.println((char)(a+1));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.