Results 1 to 4 of 4
  1. #1
    tomiu is offline Member
    Join Date
    Dec 2008
    Posts
    32
    Rep Power
    0

    Default [SOLVED] need help with rekursion

    Hi,

    can someone please explain why the output of this code is 4152?
    Java Code:
    public class rekurs1 {
    
       public static void max (int x, int y)
    	{
    		if(y>0)
    		{
    			x=x-1;
    			max(x,y-1);
    			System.out.print(x+""+y);
    		}
    	}
        public static void main(String[] args) {
            
            int i=6;
    		max(i,2);
        }
    
    }
    When max(i,2) is called in main i have
    Java Code:
    if(2>0)
    5=6-1;
    max(5,2-1)
    max is called again
    Java Code:
    if(1>0)
    4=5-1
    max(4,1-1)
    max is called for the last time and if is false
    Java Code:
    if(0>0)

    p.s. its not very urgent, i was just playing little bit with rekursion and dont understand the output

    thx in advance for ur answers

    tomiu

  2. #2
    Lynx09 is offline Member
    Join Date
    Mar 2009
    Posts
    8
    Rep Power
    0

    Default

    max(x,y-1);
    System.out.print(x+""+y);
    You know you used recursion before you used System.out.print(); method. I take it you see 0 0. 1 your method call to System.out.print() is after the method call of recursion. Instead of printing the values you already have you called the method again. 2 your method doesnt return anything. While you are calling your method and y eventually goes to zero, there wont be variables returned. Since the variables are in scope of the method in by returning to the next line after the method call the variables that to passed to the next method are in the garbage collector. Therefore y and x will be at default values zero. By putting System.out.print method before use recursion you will be able to print the values before they be passed to a different method. I personally would use System.out.println(); or System.out.print(x+" "+y" ,"); to make it easier to read the output.

  3. #3
    mrrmckenzie is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Each time you call your recursion method the JVM pushes the current state onto the stack. Since your System.out is after the recursion call the order of executing it is in reverse order. As a general guide the block of statements prior to the recursive call are executed in the order of the recursion and the remaining block of statements after the recursive call are executed in reverse as the calls are popped off the stack.

  4. #4
    tomiu is offline Member
    Join Date
    Dec 2008
    Posts
    32
    Rep Power
    0

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •