220 likes | 405 Views
Introduction to Programming. Loops. 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
E N D
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
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 iCnt = 0; while (iCnt < iSize) { //Do something iCnt = iCnt + 1;} Wait! This isn’t a For loop? iCnt < iSize F T Do something
For Loop for (iCnt=0;iCnt <=4;iCnt++) { //Do something } Ahhhhhh! That’s better! iCnt < 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.
Repeat loop • A repeat loop is a control structure where the body is repeated until the condition is true Body Condition F T
Repeat loop • When the condition is true, the body is bypassed, and flow continues with the next part of the algorithm Body Condition F T
Example: Adding Sequences iCnt = 0; iTot = 0; do { iCnt = iCnt + 1; iTot = iTot + iCnt; } while (iCnt != iSize); Body Condition F T
Recursivecall Recursion • When a subroutine or function calls itself private int sumIt(int N) { int iTotal; if (N > 0) sumIt = sumIt(N – 1) + N; else sumIt = N; }
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 on the program stack (part of memory) • But … the stack is only so big • You can run out of space!
Recursion • A better solution is to re-write the routine using a loop instead of recursion • Any ideas?
Try this! • Look up Fibonacci numbers and create a function (method) to generate the nth number