Home > front end >  Printing N times 'a' and N times 'b' using a Recursive function in Java
Printing N times 'a' and N times 'b' using a Recursive function in Java

Time:05-10

So, the following recursive function in C:

void print(int n){
    if(n==1){
       printf("ab");
     return;
    }
     putchar('a');
     print(n-1);
     putchar('b');
 }

will give you the output: aaabbb if n=3. But, i tried to 'translate' this into Java and came up with a problem. my code in Java looks like this: (which is pretty similar)

   public static void printAB(int n){
        if (n==1) {
            System.out.println("ab");
        }else {
            System.out.print("a");
            printAB(n-1);
            System.out.print("b");
        }
    }

but the output i'm getting is this:

aaab
bb

no matter what i tried i couldn't fix the last 2 'b' to be in the same line.

help please?

CodePudding user response:

Change:

System.out.println("ab");

to:

System.out.print("ab");

so there is no newline printed.

Full Code:

public static void printAB(int n) {
    if (n == 1) {
        System.out.print("ab");
    } else {
        System.out.print("a");
        printAB(n - 1);
        System.out.print("b");
    }
}

Output for printAB(3):

aaabbb
  • Related