Would anyone be able to explain these methods with a few comments line. They are for squaring a number. One is using recursion, implementation and another is just normal
public static int sq(int n)
{
int i = 0 ;
int result = 0 ;
while(i < n){
result = result + 2*i + 1 ;
i = i + 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 i ;
int result = 0 ;
for(i = 0 ; i < n ; i++){
result = result + 2*i + 1 ;
}
return result ;
}
Example: recSq(2)
reqSq(2) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 2 then we call to reqSq(1).
reqSq(1) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 1 then we call to reqSq(0).
reqSq(0) is called so we will eval the if, it's true cause n ==0 and then we return 0.
reqSq(1) call has finished evaluating reqSq(0) and then we can proceed calculating the rest 0 + 2*(n-1) + 1 -> 0 + 0 + 1. We will return the value 1.
reqSq(2) has finished evaluating reqSq(1) and then we can proceed calculating the rest 1 + 2*(n-1) +1 -> 1 + 2 + 1. We will return the value 4.