Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Loops and Files.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Computer Science 1620 Programming & Problem Solving.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Repetition Statements Repeating an Action A specified number of times While a Condition is True Until a Condition is True.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Chapter 12: How Long Can This Go On?
1. Definition and General Structure 2. Small Example 1 3. Simplified Structure 4. Short Additional Examples 5. Full Example 2 6. Common Error The for loop.
Chapter 5 Loops.
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
Coding Design Tools Rachel Gauci. What are Coding Design Tools? IPO charts (Input Process Output) Input- Make a list of what data is required (this generally.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Coding Design Tools Rachel Gauci. Task: Counting On Create a program that will print out a sequence of numbers from "1" to a "number entered”. Decision’s.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Using Loops. Goals Understand how to create while loops in JavaScript. Understand how to create do/while loops in JavaScript. Understand how to create.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Review while loops Control variables Example Infinite loop
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
Algorithms and Pseudocode
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
26/06/ Iteration Loops For … To … Next. 226/06/2016 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Loops & More 1.Conditionals (review) 2.Running totals and Running products 3.the for loop, examples 4.Nesting for loops, examples 5.Common errors 1.
REPETITION CONTROL STRUCTURE
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
CMPT 102 Introduction to Scientific Computer Programming
3.1 Iteration Loops For … To … Next 18/01/2019.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
The while Looping Structure
How to allow the program to know when to stop a loop.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1

1. General Knowledge Loops are used to repeatedly execute lines of code. There are 2 basic uses for loops 1.Make some code repeat as long as a condition is true Example: Ask for username/password until the user gives a correct combination Example: Allow the user to repeat the entire code, until s/he quits 2.Make some code repeat a certain number of times (next lecture) Example: Ask for exactly 5 grades. Note that the number of repetitions may not be known until run-time: e.g. User input tells the program how many grades to provide. 2

General Knowledge, cont. Regardless of which use, four criteria are common to both. When repeating anything, a loop needs: A starting point: “Initialization step” A decision for continuing: “Condition” A means to control the loop: “Loop control variable” An “update” step for the next iteration 3

2. Two types of loops MATLAB has two loops, one for each method explained previously: while – Generic, all-purpose. Best used when the program cannot know how many times the block of code needs to repeat. – Repeats as long as CONDITION is true. for – A counting loop. Best used when the program knows how many times the block of code needs to repeat. Convenient for the programmer. 4

The while loop 1.General Structure 2.Ex1 & 2: validating 1 input 3.Ex3: validation +1 inputs 4.Ex4: Running totals 5.Infinite while loops 5

2. General Structure General construct layout: Initialization while condition Code you wish to repeat Update of condition Note: In the block of code, the variables involved in the condition MUST be updated to avoid an infinite loop. end 6 Loop Body

1. Definition/Flowchart A while loop repeats a block of code while a condition is true. In other words: A while loop repeats the loop body until a condition becomes false. BE CAREFUL! The condition is ALWAYS written as “SHOULD IT EXECUTE AGAIN?” (not “IS IT DONE?”) 7

while condition “Again?” vs. “Done?” Common English: I want some code to execute UNTIL the user provides the value of 0. Both of the following mean the same thing to us – but only one provides a condition that works correctly in MATLAB: “Done?”“Repeat UNTIL the value is 0” “Again?” “Repeat AS LONG AS the value is not 0” WHILE loops are like IF statements – the body is executed when the condition is True. 8

while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? The “Done?” thought process will QUIT when the condition is True : “Repeat UNTIL the value is 0” Pseudo-code: repeat until value==0 code value = input(…) end-of-repeat 9

while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? The “Again?” process will REPEAT when the condition is True : “Repeat AS LONG AS the value is NOT 0” Pseudo-code: repeat as long as value ~= 0 code value = input(…) end-of-repeat 10 NOT EQUAL

while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? Always think in these terms: “When do I want the code to execute again?” In this example: “I want some code to execute until the user provides the value of 0.” I want the code to execute again when … value ~= 0 Thus, we have our WHILE loop condition 11

Examples A common use of a while loop is to 'trap the user' until s/he gives a valid input Examples: – Prompt for a radius until positive (a radius must be positive or zero) – Prompt for the number of die to roll (this value has to be strictly positive!) – Prompt for the volume of fuel to be processed into the vehicle (there is always an upper limit value) – … 12

Ex1: Validating one input Checking for a particular input that must be between (inclusive) % Initialize first reading reading = input('Enter reading (between 0-100): '); % Repeat as long as there is an error %Ask for reading again to update value 13

Ex1: Validating one input Checking for a particular input that must be between (inclusive) % Initialize first reading reading = input('Enter reading (between 0-100): '); % Repeat as long as there is an error %Ask for reading again to update value reading = input('Re-enter reading (MUST be from 0-100'); 14 Never write the loop until the body works without it!

Ex1: Validating one input Checking for a particular input that must be between (inclusive) % Initialize first reading reading = input('Enter reading (between 0-100): '); % Repeat as long as there is an error while reading 100 %Ask for reading again to update value reading = input('Re-enter reading (MUST be from 0-100'); end 15

Ex2: Numerous inputs Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt again when invalid inputs. 16

Ex2, algorithm Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt user when invalid inputs. % prompt for width until valid % prompt for height until valid % prompt for depth until valid % calculate volume of tank 17

Ex2, code % prompt for width until valid width = input('Enter a positive width (inches): '); while width<=0 width = input('ERROR: width strictly positive only --> '); end % prompt for height until valid % prompt for depth until valid % calculate volume of tank 18

Ex2, code % prompt for width until valid width = input('Enter a positive width (inches): '); while width<=0 width = input('ERROR: width strictly positive only --> '); end % prompt for height until valid height = input('\nEnter a positive height (inches): '); while height <=0 height = input('ERROR: height strictly positive only --> '); end % prompt for depth until valid % calculate volume of tank 19

Ex2, code % prompt for width until valid width = input('Enter a positive width (inches): '); while width<=0 width = input('ERROR: width strictly positive only --> '); end % prompt for height until valid height = input('\nEnter a positive height (inches): '); while height<=0 height = input('ERROR: height strictly positive only --> '); end % prompt for depth until valid depth = input('\nEnter a positive depth (inches): '); while depth<=0 depth = input('ERROR: depth strictly positive only --> '); end % calculate volume of tank volumeTankIn3 = width*height*depth; 20

Ex2, output 21

Why not all at once? Wouldn't it be easier to do this: Easier for you because it has fewer loops, but harder for the user. We force them to re-enter all of the values. 22

Ex3: Running Totals Ask user for a list of surfaces in m 2. Add all surfaces together. Stop asking when a negative/or null surface is entered! What is being done repeatedly? The program will repeatedly collect the area of a surface and add it to a total. What kind of loop? The program cannot know how many areas will be entered, so the number of times the loop will repeat is not known. Instead, the program must collect AS LONG AS (while) a strictly positive value is entered. 23

Ex4: Running Totals This code involves having a “RUNNING TOTAL”. 24

Ex4: Running Totals This code involves having a “RUNNING TOTAL”. “As the code RUNS, the TOTAL is repeatedly updated”. Note: each individual value (6,13,27) is not of any interest after it has been added in - so we're not going to try and save the individual values points 13 points 27 points Scoring Sheet.

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) 26

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero 27

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive 28

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive % “running total”: add surfaces as they are given 29

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value 30

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % start result at zero % get the first surface % As long as the current surface is positive % “running total”: add surface to total % ask for next surface value % display total surface to the screen 31

Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 32

Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 33

Ex4, block of code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value % display total surface to the screen 34

Ex4, change of condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); % display total surface to the screen 35

Ex4, fill in the code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 36

Ex4, condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 37

Ex4, continue %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen fprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 38

Ex4, output result 39

Ex4, the 3 criteria %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen fprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 40 INITIALIZATION UPDATE CONDITION Code to Repeat

Example: Infinite Loop A loop is said to be infinite if the body of the loop never stops repeating once it starts. It is caused by a loop condition that once true never becomes false. This is usually due to: – A bad initialization – A typo in the condition (wrong operators) – A code block that does not change the condition Examples x = 10; while x>0 x = x + 1; end 41 x = input('Enter x: '); while x<0 input('ERROR: enter x again: '); end

Example: Infinite Loop Omitting semi-colons is a great way to know why a loop is infinite. 42 x = 10 while x>0 x = x + 1 end >> x = 10 x = 11 x = 12 x = 13

Example: Infinite Loop 43 x = input('Enter x: ') while x<0 input('ERROR: enter x again: '); end >> Enter x: -5 x = -5 ERROR: enter x again: 5 ERROR: enter x again:

Infinite loop Infinite Loop  Once the loop has begun, the loop condition never becomes false Use CTRL+C in the command window to break it Except when the loop opens dialog boxes… then you will use alt-F4 44

Infinite loop, cont. Is this an infinite loop in MATLAB? x = 10;% 1. initialization while (x > 10)% 2. condition fprintf('%02d\n', x); x = x + 1;% 3. change loop variable end 45 An infinite loop is not the same thing as a program that doesn't quit. You can have an infinite loop in a program that quits just fine. It is the loop that is infinite – not necessarily the program.

Key Ideas A while loop repeats a block of code as long as a condition is true. Structure: Initialization, while condition, code to be repeated, update of condition, end Common Uses: – trap the user until a valid input is given (relational operators, boolean operators, even, odd, integers, etc.) – running total until a condition is met Infinite loop occurs when the loop condition is never becomes false from within the loop body. – To stop an infinite loop: Ctrl-C in the command window 46