Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops CS 103 February 19, 2007 Presented by Nate.

Similar presentations


Presentation on theme: "Loops CS 103 February 19, 2007 Presented by Nate."— Presentation transcript:

1 Loops CS 103 February 19, 2007 Presented by Nate

2 Announcements Final group project teams posted on Blackboard Final group project teams posted on Blackboard Coversheets have been distributed Coversheets have been distributed Submission issues Submission issues You must submit BOTH online and hardcopy versionsYou must submit BOTH online and hardcopy versions Hard copies and online versions must be IDENTICALHard copies and online versions must be IDENTICAL Exam 1 statistics Exam 1 statistics Section 1 Section 2 Overall 574949 10099100 85.681.984.1 MINMAX AVG

3 Quick Review W = 10; X = 12; Y = 4; Z = 19; IF Z = 4)*W) = 4)*W) <= 10 IF X > 12 fprintf('I love school.\n'); ELSEIF X < 17 IF Y > 5 & W > 5 fprintf('I hate Rand\n'); ELSEIF Y < 4 | W < 10 fprintf('I love Spring Break!!!\n'); ELSE fprintf(‘Why do I even bother coming to class?\n'); ENDELSE fprintf(‘Hmmm...I wonder how I got back to my room last night...\n'); ENDELSE fprintf(‘I am so confused.\n’); END

4 What is a loop? A control construct that allows for a block of code to be repeated A control construct that allows for a block of code to be repeated In Matlab, loops come in two forms: In Matlab, loops come in two forms: FOR loopsFOR loops WHILE loopsWHILE loops

5 FOR Loops Syntax: Syntax: FOR variable = expression statementsEND

6 FOR Loops FOR variable = expression statementsEND The variable is known as an index, and can be treated as a variable by the program. Traditionally, the letter i is used as the index, but in Matlab, i also is used to represent imaginary numbers, so we use ii or another letter.

7 FOR Loops FOR variable = expression statementsEND In FOR loops, the expression is a counting mechanism. We typically use the colon operator to define how many times the loop should run. For example, 1:10 means to run the loop 10 times (from one to ten)

8 FOR Loops FOR variable = expression statementsEND The statements are the set of code which is to be executed over and over again during the loop. Every loop needs to conclude with an END

9 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END

10 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Before the loop, ii doesn’t exist

11 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END First time through, ii = 1

12 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END First time through, ii = 1 Now we print Count: 1

13 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END First time through, ii = 1 Now we print Count: 1 The loop ends, so we’ll return to the top of the loop

14 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Second time through, so ii is incremented ii = 2

15 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Second time through, ii = 2 Now we print Count: 2

16 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Second time through, ii = 2 Now we print Count: 2 The loop ends, so we’ll return to the top of the loop

17 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Third time through, ii = 3

18 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Third time through, ii = 3 Now we print Count: 3 This will continue for awhile…

19 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Imagine we’re now on the 9 th iteration Ninth time through, ii = 9 Now we print Count: 9 The loop ends, so we’ll return to the top of the loop

20 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Tenth time through, ii = 10 This will be the last time we go through the loop!

21 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Tenth time through, ii = 10 Now we print Count: 10

22 Example: Count to 10 FOR ii = 1:10 fprintf(‘\n Count: %d’, ii) END Tenth time through, ii = 10 Now we print Count: 10 We’ve run the loop 10 times….because that’s as far as we have been asked to go, the loop ends and we’ll go on to whatever code exists after the end statement.

23 Notes About FOR Loops Used when the required values of your index variable are known before the loop begins Though not necessarily before the program begins. Used when the required values of your index variable are known before the loop begins Though not necessarily before the program begins. Example: count to 10, add 12 numbers, calculate pi to 30 decimal places, etc. Example: count to 10, add 12 numbers, calculate pi to 30 decimal places, etc.

24 FOR Loop Example Suppose we wanted to write a program that prints out all the positive numbers in an array, X, with each element on a separate line Suppose we wanted to write a program that prints out all the positive numbers in an array, X, with each element on a separate line X = [-2 4 6 -7 3 5 -45 1 -.5 2.6] X = [-2 4 6 -7 3 5 -45 1 -.5 2.6]

25 FOR Loop Example Suppose we wanted to write a program that prints out all the positive numbers in an array, x Suppose we wanted to write a program that prints out all the positive numbers in an array, x X = [-2 4 6 -7 3 5 -45 1 -.5 2.6] X = [-2 4 6 -7 3 5 -45 1 -.5 2.6] FOR ii = 1:10 if x(ii) > 0 fprintf(‘%f \n’, x(ii)) endEND But what happens if instead, we ask the user to input x first? Will we know how many elements are in x? But what happens if instead, we ask the user to input x first? Will we know how many elements are in x?

26 Working Around the Number Limitation When working with an array of numbers that may change, you can use the length function. FOR ii = 1:length(x) When working with an array of numbers that may change, you can use the length function. FOR ii = 1:length(x)

27 FOR Loop Example Ask the user to input an array, x, and then print out all the positive numbers in the array. Ask the user to input an array, x, and then print out all the positive numbers in the array. X = input(‘Please give me an array: ‘) FOR ii = 1:length(x) if x(ii) > 0 fprintf(‘%f \n’, x(ii)) endEND

28 Easy Question Think about this first: Write a FOR loop that will determine if a vector contains a “perfect sandwich.” That is, for any element x(i) in vector X such that x(i-1) and x(i+1) are defined, does the following condition hold? (x(i-1) + 1) = x(i) = (x(i+1) – 1) Think about this first: Write a FOR loop that will determine if a vector contains a “perfect sandwich.” That is, for any element x(i) in vector X such that x(i-1) and x(i+1) are defined, does the following condition hold? (x(i-1) + 1) = x(i) = (x(i+1) – 1) What if the condition must hold for ALL elements x(i)? What would X look like? How could you check X? What if the condition must hold for ALL elements x(i)? What would X look like? How could you check X?

29 Harder Question Borrowing from the previous example, suppose the sandwich is not required to consist of consecutive elements (but still must consist of 3 equally spaced elements). Borrowing from the previous example, suppose the sandwich is not required to consist of consecutive elements (but still must consist of 3 equally spaced elements). Is there a way to check X? Is there a way to check X? And then what if the elements are not required to be equally spaced? And then what if the elements are not required to be equally spaced?

30 Any Questions So Far?

31 While Loops Syntax: Syntax: WHILE expression statements statementsend

32 While Loops WHILE expression statements statementsend Unlike a for loop, the expression in a while loop consists of a logical or relational test. As long as that test evaluates to true, the loop will continue Unlike a for loop, the expression in a while loop consists of a logical or relational test. As long as that test evaluates to true, the loop will continue

33 Example n = 1 while n < 100 fprintf(‘x = %3.0f\n’, n); n = n + 1; end

34 Indexing WHILE loops do not have their own built-in index! WHILE loops do not have their own built-in index! If your program needs an index, you’ll have to create it yourself. If your program needs an index, you’ll have to create it yourself. You’ll also have to increment it yourself. You’ll also have to increment it yourself.

35 Try It Out... Write a WHILE loop that prints the squares from 1 to 10 Write a WHILE loop that prints the squares from 1 to 10

36 Now Try This... Given the array x = [1 2 7 21 -5 6 9] write a WHILE loop that calculates and prints the square of each value in the array Given the array x = [1 2 7 21 -5 6 9] write a WHILE loop that calculates and prints the square of each value in the array Make this program robust by writing code that will allow me to change the value of x later and still have the code run. (HINT: use length(x) ) Make this program robust by writing code that will allow me to change the value of x later and still have the code run. (HINT: use length(x) )

37 Pitfall Avoidance Your logical or relational expression has to be able to handle the endpoints of your array properly Your logical or relational expression has to be able to handle the endpoints of your array properly Consider the following workarounds: n <= length(x) n < (length(x) + 1) Consider the following workarounds: n <= length(x) n < (length(x) + 1)

38 BREAK and CONTINUE Satements break statement: BREAK statement BREAK statement terminates the execution of FOR and WHILE loops.terminates the execution of FOR and WHILE loops. In nested loops, BREAK exits from the innermost loop only.In nested loops, BREAK exits from the innermost loop only. BREAK is not defined outside of a FOR or WHILE loop. Use RETURN in this context instead.BREAK is not defined outside of a FOR or WHILE loop. Use RETURN in this context instead. CONTINUE statement CONTINUE statement passes control to the next iteration of FOR or WHILE loop in which it appears, skipping any remaining statements in the body of the FOR or WHILE loop.passes control to the next iteration of FOR or WHILE loop in which it appears, skipping any remaining statements in the body of the FOR or WHILE loop. In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop enclosing it.In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop enclosing it.

39 Questions?


Download ppt "Loops CS 103 February 19, 2007 Presented by Nate."

Similar presentations


Ads by Google