Loops CS 103 February 19, 2007 Presented by Nate.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
ITC 240: Web Application Programming
Computer Science 1620 Loops.
MatLab – Palm Chapter 4, Part 3 For and While Loops
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Chapter 5: Control Structures II (Repetition)
Loops – While, Do, For Repetition Statements Introduction to Arrays
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 6: Loop Control Structures.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
JavaScript Switch Statement. Switch JavaScript Switch Statement If you have a lot of conditions, you can use a switch statement instead of an if…elseif…
The switch Statement, DecimalFormat, and Introduction to Looping
CS0007: Introduction to Computer Programming Introduction to Arrays.
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Matlab Programming for Engineers
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Loops CS 103 February 13, 2009 Author: Nate Hamm.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu.
Loops CS 103 February 23, Review FOR is a control construct that provides a loop for ii = 1:10 fprintf(‘%d \n’, ii) end FOR is a control construct.
COMP Loop Statements Yi Hong May 21, 2015.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Loop Applications and Review CS 103 February 27, 2004.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
CSE123 - Lecture 4 Structured Programming- Loops.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Matlab Training Session 4: Control, Flow and Functions
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Chapter 5: Control Structures II
CS1371 Introduction to Computing for Engineers
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
3 Control Statements:.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Computing Fundamentals
ECE 103 Engineering Programming Chapter 18 Iteration
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Loops CS 103 February 19, 2007 Presented by Nate

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 MINMAX AVG

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

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

FOR Loops Syntax: Syntax: FOR variable = expression statementsEND

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.

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)

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

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

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

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

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

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

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

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

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

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

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…

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

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!

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

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.

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.

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 = [ ] X = [ ]

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 = [ ] X = [ ] 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?

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)

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

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?

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?

Any Questions So Far?

While Loops Syntax: Syntax: WHILE expression statements statementsend

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

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

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.

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

Now Try This... Given the array x = [ ] write a WHILE loop that calculates and prints the square of each value in the array Given the array x = [ ] 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) )

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)

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.

Questions?