-6

What would be the Output of this program and how it would be?

public class Recursion 
{
    static int p=100;
    public static void main(String args[])
    {
        divide(20);
    }
    public static void divide(int x)
    {
        System.out.println(x);
        if(x>1)
        {
            divide(x/2);
            divide(x/4);
        }
        //System.out.println(x);

    }
    public static void multiply(int x)
    {
        System.out.println("X="+x);
    }

}

Please provide the output and its working.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

0

This modification can help you understand the order of calls. (It just adds context to your system.out.println())

public class StackOverflowQuestions {

    public static void main(String args[]) {
        divide(20, "x=20, depth=0, initial call", 1);
    }

    public static void divide(int x, String callOrder, int depth) {
        System.out.println(callOrder);
        if (x > 1) {
            divide(x / 2, callOrder+" ; x="+x/2+",depth="+depth+",call=1", depth+1);
            divide(x / 4, callOrder+" ; x="+x/4+",depth="+depth+",call=2", depth+1);
        }
    }

}

And here is the output:

x=20, depth=0, initial call
x=20, depth=0, initial call ; x=10,depth=1,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=1,depth=4,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=0,depth=4,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=1,depth=3,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=1,depth=2,call=2

As you can see, the first of your two method calls is always used until your break condition of x<=1 is met. Only then does the program reach the second line and the same recursive calls happen once more until the break condition is met here as well.