Hmm
Hmm

Reputation: 79

Printing (char) A through (n) recursively

I seem to be close, but I can't seem to figure out a way to print out the original letter. With my current code, if I input "e", I want to print out a b c d e. However, my code only prints out a b c d, and not e. I know this is because 'c' gets subtracted because it can print out e, but I can't figure out how to print it out from e to a while printing it out backwards.

public static void letters(char c)
{
    if (c > 'a')
    {
        letters(--c);
    } else {
        return;
    }
    System.out.print(c + " ");
}

Upvotes: 2

Views: 593

Answers (1)

luk2302
luk2302

Reputation: 57184

You decrement c and then later eventually print it which means you will never print the original value. Change your code to

public static void letters(char c) {
    if (c > 'a') {
        letters((char)(c - 1)); // do not decrement c
    } // no else block since we dont need it
    System.out.print(c + " ");
}

Upvotes: 4

Related Questions