Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ul> <li>The first one is multiplying the number by 2 n times using a loop to increase a local variable i.</li> <li>The second one is doing exactly the same but using recursion. Each step decreasing n and returning 0 for the final case. All the calls are calling again to the same function with different parameters exept for the parameter value 0, then the function will return 0. Recursion is not a simple thing to think off, to understand it better try to imagine the codeflow.</li> </ul> <p>Example: recSq(2)</p> <pre><code> 4 recSq(2) |&lt;- 1 reqSq(1)+2*1+1 |&lt;-0 reqSq(0)+2*0 + 1 |&lt;- 0 </code></pre> <p>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).</p> <p>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).</p> <p>reqSq(0) is called so we will eval the if, it's true cause n ==0 and then we return 0.</p> <p>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.</p> <p>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.</p> <ul> <li>The last one is a for loop, practically the same as the first one but using fors instead of while loops. In a for loop you declare in one line the initialization condition, the continue condition and the increase operation. So in that case the for loop is starting with value 0, the loop will continue as i &lt; n and at the end of the loop "i++" will be called.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload