recursion - Java Square function -
would able explain these methods few comments line. squaring number. 1 using recursion, implementation , normal
public static int sq(int n) { int = 0 ; int result = 0 ; while(i < n){ result = result + 2*i + 1 ; = + 1 ; } return result ; } public static int recsq(int n) { if(n == 0){ return 0 ; } else { return recsq(n - 1) + 2*(n - 1) + 1 ; } } public static int implementsq(int n) { int ; int result = 0 ; for(i = 0 ; < n ; i++){ result = result + 2*i + 1 ; } return result ; }
- the first 1 multiplying number 2 n times using loop increase local variable i.
- the second 1 doing same using recursion. each step decreasing n , returning 0 final case. calls calling again same function different parameters exept parameter value 0, function return 0. recursion not simple thing think off, understand better try imagine codeflow.
example: recsq(2)
4 recsq(2) |<- 1 reqsq(1)+2*1+1 |<-0 reqsq(0)+2*0 + 1 |<- 0
reqsq(2) called eval if , start evaluating return statement. first operation method call reqsq(n-1) n = 2 call reqsq(1).
reqsq(1) called eval if , start evaluating return statement. first operation method call reqsq(n-1) n = 1 call reqsq(0).
reqsq(0) called eval if, it's true cause n ==0 , return 0.
reqsq(1) call has finished evaluating reqsq(0) , can proceed calculating rest 0 + 2*(n-1) + 1 -> 0 + 0 + 1. return value 1.
reqsq(2) has finished evaluating reqsq(1) , can proceed calculating rest 1 + 2*(n-1) +1 -> 1 + 2 + 1. return value 4.
- the last 1 loop, practically same first 1 using fors instead of while loops. in loop declare in 1 line initialization condition, continue condition , increase operation. in case loop starting value 0, loop continue < n , @ end of loop "i++" called.