Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing N times 'a' and N times 'b' using a Recursive function in Java

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

aaab
bb

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

help please?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading