recursion in java with unexpected output -
public class testing { public static void printnum(int a) { system.out.println( a); if(a <= 3) { system.out.println("recursed"); printnum(a+1); } system.out.println( a); } public static void main(string...s) { printnum(1); } }
output:
1 2 3 3 2 1
i expected program end @ last 3 not understand next '2' , '1' coming from? how , why decrementing?
you've got 2 calls system.out.println(a)
. you'll find easier understand if differentiate between them:
public static void printnum(int a) { system.out.println("before recursion: " + a); if(a <= 3) { system.out.println("recursing"); printnum(a + 1); } system.out.println("after recursion: " + a); }
basically, calls nest - nested call print:
before recursion: 4 after recursion: 4
... , return call printnum(3)
, print:
after recursion: 3
and return call printnum(2)
, print
after recursion: 2
etc.
now time learn how use debugger step through code, @ stack @ every point, etc.
Comments
Post a Comment