Loops CS 103 February 19, 2007 Presented by Nate.
-
Upload
jack-watson -
Category
Documents
-
view
218 -
download
0
Transcript of Loops CS 103 February 19, 2007 Presented by Nate.
LoopsLoops
CS 103CS 103
February 19, 2007February 19, 2007
Presented by Nate
AnnouncementsAnnouncements
Final group project teams posted on BlackboardFinal group project teams posted on Blackboard Coversheets have been distributedCoversheets have been distributed Submission issuesSubmission 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 statisticsExam 1 statistics
Section 1Section 1 Section 2Section 2 OverallOverall
5757 4949 4949
100100 9999 100100
85.685.6 81.981.9 84.184.1
MINMIN
MAXMAX
AVGAVG
Quick ReviewQuick ReviewW = 10;W = 10;X = 12;X = 12;Y = 4;Y = 4;Z = 19;Z = 19;IF Z <= 19 & ((Y >= 4)*W) <= 10IF Z <= 19 & ((Y >= 4)*W) <= 10
IF X > 12IF X > 12fprintf('I love school.\n');fprintf('I love school.\n');
ELSEIF X < 17ELSEIF X < 17IF Y > 5 & W > 5IF Y > 5 & W > 5
fprintf('I hate Rand\n');fprintf('I hate Rand\n');ELSEIF Y < 4 | W < 10ELSEIF Y < 4 | W < 10
fprintf('I love Spring Break!!!\n');fprintf('I love Spring Break!!!\n');ELSEELSE
fprintf(‘Why do I even bother coming to class?\n');fprintf(‘Why do I even bother coming to class?\n');ENDEND
ELSEELSEfprintf(‘Hmmm...I wonder how I got back to my room last night...\n');fprintf(‘Hmmm...I wonder how I got back to my room last night...\n');
ENDENDELSEELSE
fprintf(‘I am so confused.\n’);fprintf(‘I am so confused.\n’);ENDEND
What is a lWhat is a loooop?p?
A control construct that allows for a block A control construct that allows for a block of code to be repeatedof code to be repeated
In Matlab, loops come in two forms:In Matlab, loops come in two forms:• FOR loopsFOR loops• WHILE loopsWHILE loops
FOR LoopsFOR Loops
Syntax:Syntax:
FOR variable = expressionFOR variable = expression
statementsstatements
ENDEND
FOR LoopsFOR Loops
FOR FOR variablevariable = expression = expressionstatementsstatements
ENDEND
The The variablevariable is known as an is known as an indexindex, and can be , and can be treated as a variable by the program.treated as a variable by the program.
Traditionally, the letter i is used as the index, Traditionally, the letter i is used as the index, but in Matlab, i also is used to represent but in Matlab, i also is used to represent imaginary numbers, so we use ii or another imaginary numbers, so we use ii or another letter.letter.
FOR LoopsFOR Loops
FOR variable = FOR variable = expressionexpression
statementsstatements
ENDEND
In FOR loops, the In FOR loops, the expressionexpression is a counting is a counting mechanism. We typically use the colon mechanism. We typically use the colon operator to define how many times the operator to define how many times the loop should run. For example, 1:10 means loop should run. For example, 1:10 means to run the loop 10 times (from one to ten)to run the loop 10 times (from one to ten)
FOR LoopsFOR Loops
FOR variable = expressionFOR variable = expression
statementsstatements
ENDEND
The The statementsstatements are the set of code which is are the set of code which is to be executed over and over again during to be executed over and over again during the loop.the loop.
Every loop needs to conclude with an Every loop needs to conclude with an ENDEND
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Before the loop, ii doesn’t exist
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
First time through,
ii = 1
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
First time through, ii = 1
Now we print Count: 1
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
First time through, ii = 1
Now we print Count: 1
The loop ends, so we’ll return to the top of the loop
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Second time through, so ii is incremented
ii = 2
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Second time through, ii = 2
Now we print Count: 2
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Second time through, ii = 2
Now we print Count: 2
The loop ends, so we’ll return to the top of the loop
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Third time through,
ii = 3
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Third time through, ii = 3
Now we print Count: 3
This will continue for awhile…
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Imagine we’re now on the 9th iteration
Ninth time through, ii = 9
Now we print Count: 9
The loop ends, so we’ll return to the top of the loop
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Tenth time through,
ii = 10
This will be the last time we go through the loop!
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
Tenth time through, ii = 10
Now we print Count: 10
Example: Count to 10Example: Count to 10
FOR ii = 1:10FOR ii = 1:10
fprintf(‘\n Count: %d’, ii)fprintf(‘\n Count: %d’, ii)
ENDEND
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.
Notes About FOR LoopsNotes About FOR Loops
Used when the required values of Used when the required values of your index variable are known before your index variable are known before the loop beginsthe loop begins
Though not necessarily before the Though not necessarily before the program begins.program begins.
Example: count to 10, add 12 Example: count to 10, add 12 numbers, calculate pi to 30 decimal numbers, calculate pi to 30 decimal places, etc.places, etc.
FOR Loop ExampleFOR Loop Example
Suppose we wanted to write a Suppose we wanted to write a program that prints out all the program that prints out all the positive numbers in an array, X, with positive numbers in an array, X, with each element on a separate lineeach 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]
FOR Loop ExampleFOR Loop Example Suppose we wanted to write a program that Suppose we wanted to write a program that
prints out all the positive numbers in an array, xprints 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:10FOR ii = 1:10if x(ii) > 0if x(ii) > 0
fprintf(‘%f \n’, x(ii))fprintf(‘%f \n’, x(ii))endend
ENDEND
But what happens if instead, we ask the user to But what happens if instead, we ask the user to input x first? Will we know how many elements input x first? Will we know how many elements are in x?are in x?
Working Around the Number Working Around the Number LimitationLimitation
When working with an array of When working with an array of numbers that may change, you can numbers that may change, you can use the length function.use the length function.
FOR ii = 1:length(x) FOR ii = 1:length(x)
FOR Loop ExampleFOR Loop Example
Ask the user to input an array, x, and then Ask the user to input an array, x, and then print out all the positive numbers in the print out all the positive numbers in the array.array.
X = input(‘Please give me an array: ‘)X = input(‘Please give me an array: ‘)FOR ii = 1:length(x)FOR ii = 1:length(x)
if x(ii) > 0if x(ii) > 0fprintf(‘%f \n’, x(ii))fprintf(‘%f \n’, x(ii))
endendENDEND
Easy QuestionEasy Question Think about this first:Think about this first:
Write a FOR loop that will determine if a vector Write a FOR loop that will determine if a vector contains a “perfect sandwich.”contains a “perfect sandwich.”
That is, for any element x(i) in vector X such that That is, for any element x(i) in vector X such that x(i-1) and x(i+1) are defined, does the following x(i-1) and x(i+1) are defined, does the following condition hold?condition hold?
(x(i-1) + 1) = x(i) = (x(i+1) – 1)(x(i-1) + 1) = x(i) = (x(i+1) – 1)
What if the condition must hold for ALL elements What if the condition must hold for ALL elements x(i)? What would X look like? How could you x(i)? What would X look like? How could you check X?check X?
Harder QuestionHarder Question
Borrowing from the previous Borrowing from the previous example, suppose the sandwich is example, suppose the sandwich is not required to consist of consecutive not required to consist of consecutive elements (but still must consist of 3 elements (but still must consist of 3 equally spaced elements).equally spaced elements).
Is there a way to check X?Is there a way to check X? And then what if the elements are And then what if the elements are
not required to be equally spaced?not required to be equally spaced?
Any Questions So Far?Any Questions So Far?
While LoopsWhile Loops
Syntax:Syntax:
WHILE expressionWHILE expression
statementsstatements
endend
While LoopsWhile Loops
WHILE WHILE expressionexpression statementsstatementsendend
Unlike a for loop, the Unlike a for loop, the expressionexpression in a in a while loop consists of a logical or while loop consists of a logical or relational test. As long as that test relational test. As long as that test evaluates to true, the loop will evaluates to true, the loop will continuecontinue
ExampleExample
n = 1n = 1
while n < 100while n < 100
fprintf(‘x = %3.0f\n’, n);fprintf(‘x = %3.0f\n’, n);
n = n + 1;n = n + 1;
endend
IndexingIndexing
WHILE loops do not have their own WHILE loops do not have their own built-in index!built-in index!
If your program needs an index, If your program needs an index, you’ll have to create it yourself.you’ll have to create it yourself.
You’ll also have to increment it You’ll also have to increment it yourself.yourself.
Try It Out. . .Try It Out. . .
Write a WHILE loop that prints the Write a WHILE loop that prints the squares from 1 to 10squares from 1 to 10
Now Try This. . .Now Try This. . .
Given the array x = [1 2 7 21 -5 6 Given the array x = [1 2 7 21 -5 6 9] write a WHILE loop that 9] write a WHILE loop that calculates and prints the square of calculates and prints the square of each value in the arrayeach value in the array
Make this program robust by writing Make this program robust by writing code that will allow me to change the code that will allow me to change the value of x later and still have the value of x later and still have the code run. (HINT: use length(x) )code run. (HINT: use length(x) )
Pitfall AvoidancePitfall Avoidance
Your logical or relational expression Your logical or relational expression has to be able to handle the has to be able to handle the endpoints of your array properlyendpoints of your array properly
Consider the following workarounds:Consider the following workarounds:n <= length(x)n <= length(x)n < (length(x) + 1)n < (length(x) + 1)
BREAK and CONTINUE BREAK and CONTINUE SatementsSatements
break statement:break statement: BREAK statementBREAK 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 In nested loops, BREAK exits from the innermost loop
only. only. • BREAK is not defined outside of a FOR or WHILE loop. BREAK is not defined outside of a FOR or WHILE loop.
Use RETURN in this context instead.Use RETURN in this context instead. CONTINUE statementCONTINUE statement
• passes control to the next iteration of FOR or WHILE loop passes control to the next iteration of FOR or WHILE loop in which it appears, skipping any remaining statements in which it appears, skipping any remaining statements in the body of the FOR or WHILE loop.in the body of the FOR or WHILE loop.
• In nested loops, CONTINUE passes control to the next In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop enclosing it.iteration of FOR or WHILE loop enclosing it.
Questions?Questions?