150 likes | 330 Views
Loops. Website Production. Q: What is a Loop?. A control structure that allows for a sequence of steps to be repeated a certain number of times This sequence of steps is called the body of the loop. Q: What is a Loop?. There are three basic loop structures in programming: For While
E N D
Loops Website Production
Q: What is a Loop? • A control structure that allows for a sequence of steps to be repeated a certain number of times • This sequence of steps is called the body of the loop
Q: What is a Loop? • There are three basic loop structures in programming: • For • While • Repeat (not in Javascript)
While loop • A while loop is a control structure where the body is repeated as long as the condition is true Condition F T Body
While loop • When the condition is false, the body is bypassed, and flow continues with the next part of the algorithm Condition F T Body
Example: Adding Sequences k 0 total 0 while (k<size) k k + 1 total total + k (k<size) F T k k + 1 total total + k
Example: Adding Sequences iCnt = 0; iTot = 0; while (iCnt<iSize){ iCnt = iCnt + 1; iTot = iTot + iCnt; } iCnt < iSize F T iCnt = iCnt + 1 iTot = iTot + iCnt
For Loop i = 0; while (i < iSize){ //Do something i = i + 1;} Wait! This isn’t a For loop? iCnt < iSize F T Do something
Initialize counter Test for end condition Increment counter For Loop for (i=0; i<iSize; i++){ //Do something} Ahhhhhh! That’s better! i < iSize F T Do something
Exercise • The function factorial (n!) is defined as the product of the integers 1 through n. • Create two functions to compute n!, the first version using a for loop and the second using a while loop.
Recursivecall Recursion • When a subroutine or function calls itself function sumIt(N){ if (N > 0) out = sumIt(N – 1) + N; else out = N; return out; }
sumIt 4 + 6 sumIt(3) sumIt 3 + 3 sumIt(2) sumIt 2 + 1 sumIt(1) sumIt 1 + 0 sumIt(0) sumIt 0 Recursion Example: sumIt(4)
Recursion • But … there’s only so far down we can go • Question : How many recursive calls would it take to evaluate sumIt(10000)?
Recursion • Each time you make a recursive call, the state of the calling routine is saved in memory • But …You can run out of space!
Recursion • A better solution is to re-write the routine using a loop instead of recursion • Any ideas?