Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Tracing Recursion - in Java Printing #1 public void p1(int n) { if (n > 1) { p1(

ID: 3572651 • Letter: T

Question

Tracing Recursion - in Java

Printing #1

public void p1(int n)

{

   if (n > 1)

   {

      p1(n-1);

      System.out.print(n);

      p1(n-1);

   }

}

What does p1(4) print?

What does p1(5) print?

Printing #2

public void p2(int n)

{

   if (n > 0)

   {

      for (int i = 0; i < n; i++)

         System.out.print(i);

      System.out.println();

      p2(n-1);

   }

}

What does p2(4) print?

Printing #3

public void p3(int n)

{

   if (n > 0)

   {

      p3(n-1);

      for (int i = 0; i < n; i++)

         System.out.print(i);

      System.out.println();

   }

}

What does p3(4) print?

Printing #4

public void p4(int n)

{

   if (n > 0)

   {

      System.out.print(n % 10);

      p4(n / 10);

   }

}

What does p4(1234) print?

Printing #5

public void p5(int n)

{

   if (n > 0)

   {

      p5(n / 2);

      System.out.print(n % 2);

   }

}

What does p5(20) print?

Explanation / Answer

Please follow the code and comments for description :

a)

CODE :

public class aClass {

    public static void main(String[] args) {
        p1(4);
    }

    public static void p1(int n) {

        if (n > 1) {

            p1(n - 1);

            System.out.print(n);

            p1(n - 1);

        }

    }

}

OUTPUT :

1) for p1(4) :

2324232

2) for p1(5) :

232423252324232

b)

CODE :

public class NewClass {

    public static void main(String[] args) {
        p2(4);
    }

    public static void p2(int n) {

        if (n > 0) {

            for (int i = 0; i < n; i++) {
                System.out.print(i);
            }

            System.out.println();

            p2(n - 1);

        }

    }

}


OUTPUT :

0123
012
01
0

c)

CODE :

public class cClass {

    public static void main(String[] args) {
        p3(4);
    }

    public static void p3(int n) {

        if (n > 0) {

            p3(n - 1);

            for (int i = 0; i < n; i++) {
                System.out.print(i);
            }

            System.out.println();

        }

    }

}

OUTPUT :

0
01
012
0123

d)

CODE :

public class dClass {

    public static void main(String[] args) {
        p4(1234);
    }

    public static void p4(int n) {

        if (n > 0) {

            System.out.print(n % 10);

            p4(n / 10);

        }

    }

}

OUTPUT :

4321

e)

public class eClass {

    public static void main(String[] args) {
        p5(20);
    }

    public static void p5(int n) {

        if (n > 0) {

            p5(n / 2);

            System.out.print(n % 2);

        }

    }
}

OUTPUT :

10100

Hope this is helpful.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote