Wednesday, 15 February 2012

recursion - JAVA Recursive Program logic -



recursion - JAVA Recursive Program logic -

public class prod { public static void main(string[] args) { system.out.println(prod(1, 4)); } public static int prod(int m, int n) { if (m == n) { homecoming n; } else { int recurse = prod(m, n-1); int result = n * recurse; homecoming result; } } }

on running above code , 24 ? don't quite understand how?

my doubts: 1. when m =1 , n=4 , phone call prod until m , n become equal 1. output should n , else block should not executed??

someone please help me understand logic.

just run through numbers, need write downwards see behavior (in future, suggest adding lots of prints code check variables , how alter each pass through).

prod(1,4) m=1,n=4 m != n so, recurse = prod(1, 3) prod(1, 3) m=1,n=3 m != n so, recurse = prod(1, 2) prod(1, 2) m=1,n=2 m != n so, recurse = prod(1, 1) prod(1, 1) m=1,n=1 m == n so, homecoming 1 returns prod(1, 2) recurse = 1 result = 2 * 1 homecoming 2 returns prod(1, 3) recurse = 2 result = 3 * 2 homecoming 6 returns prod(1, 4) recurse = 6 result = 4 * 6 homecoming 24

thus, programme prints 24.

sometimes best way figure out programme mechanically go through steps line line, executing them in head (or on paper track things).

java recursion

No comments:

Post a Comment