java - Recursion Tutorial -
i learning java book, , come across chapter regarding recursion using factorial example.
//a simple example of recursion package tutorials; class factorial { // recursive method int fact (int n) { int result; if(n==1) return 1; result = fact(n - 1) * n; return result; } } class recursion { public static void main(string args[]) { factorial f = new factorial(); system.out.println("factorial of 3 " + f.fact(3)); system.out.println("factorial of 4 " + f.fact(4)); system.out.println("factorial of 5 " + f.fact(5)); } }
the result piece of code gives "factorial of 3 6" , "factorial of 4 24"
what don't understand happening in class factorial , why *n not calculated immediately. book not job of explaining thought ask experienced programmers help.
if invoke fact(5)
, here how work:
fact(5) 5*fact(4) 4*fact(3) 3*fact(2) 2*fact(1) 2*1=2 //(since if n==1, 1 returned directly result=2 result=3*2 result=4*3*2 result=5*4*3*2 result=120
recursion means invoke method within itself, after manipulating argument suit end result (n - 1
in case). make sure define terminal condition (n==1
in case). internally, variables pushed on stack remembered every invocation, that's discussion day
Comments
Post a Comment