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.

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

LOOP / REPETITION while loop. for loop do/while loop We assume that loops are not meant to be infinite. That is, there should always be a way out of the.
Objectives In this chapter, you will learn about:
Repeating Actions While and For Loops
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Sentinel Logic Assumes while loops and input statements.
Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures.
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.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Programming Logic and Design Fifth Edition, Comprehensive
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
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.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Chapter Making Decisions 4. Relational Operators 4.1.
Data Validation while loops. Data validation Programs get input data from different sources All data should be ‘validated’ before the program tries to.
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.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
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.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
The switch Statement, and Introduction to Looping
Chapter 4: Making Decisions.
Loop Structures.
JavaScript: Control Statements.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Control Structures - Repetition
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Chapter 6: Repetition Statements
Topics Introduction to Repetition Structures
Repetition Statements (Loops) - 2
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.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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 called definite loops because we know how many times the loop needs to be executed There are situations where loops are needed but there is no way to determine ahead of time how many times they will run, this is an indefinite loop This is where a while loop becomes useful Anything that you can do with a for loop, you can do with an equivalent while loop There are things that can be done with a while which cannot be done with a for loop (at least, without using break!)

For loops To control a for loop you can use range function- range(10) iterates the variable from 0 to 9 a list- for i in [3, 9, 23, ‘a’, True]: (i gets every value in the list in that order) a string- for i in name: (i gets each character in the string in that order) (future) a file- for myline in infile: (myline gets each line in the file in turn)

While loop syntax while Boolean condition: body statements The Boolean condition is just like the ones in the if statements The body has to have at least one line, it can be as long as you like

While loop semantics When executing, the Boolean condition at the top is done first If it’s False, the body is skipped and execution continues with the next statement after the body (so the body may not be executed at all!) This is why a while loop is called a “pre-test” loop If the test is True, the body is executed the whole way through, then the Boolean condition at the top is evaluated again As long as the test stays True, the body will be executed It is possible to have an infinite loop, if the condition never changes – this is a bug!

While statement semantics

Controlling while loops You can control a while loop with a counter It is a little more code than for the equivalent for loop The other way to control a while loop is more general Any condition can be used as the Boolean expression at the top You can use user input (see Sentinel Logic) You can use calculations (“until the number reaches a given value”) You can use a flag that indicates some condition that occurred inside the loop

Sentinel Logic Assumes while loops and input statements

Sentinel Logic – uses an indefinite loop The for loop is a definite loop – you know how many times it needs to execute There are many situations in life / programming where you do not know this information (how many times it needs to execute) The while loop (indefinite loop) is made for this kind of situation. Example: “The loop executes until a sensor gives a value out of range” Example: “The user plays a game until they get tired.” Example: “The user inputs a value which must be either Y or N, nothing else.”

A pattern A pattern of statements called “sentinel logic” handles this kind of problem as cleanly as it can be done. A sentinel is an indicator that the loop can stop executing, that the data is used up. It can be a special number (-1, 0, 9999), a string (“stop”), or it can be a condition (keep looping while sensor > 0 and sensor < 50) Pattern Input the first data value to be processed While the data value is not the sentinel Process the data value Input the next data value to be processed

Nested Loops

Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures can be nested inside each other to any degree you need

Nested loops The general principle of nesting loops is that the inner loop must completely finish its execution before the next iteration of the outer loop starts Every time the outer loop iterates, the inner loop needs to start the control variable back at the beginning again

Nested for loops for i in range(10): for j in range(5): print(i, j) The nesting is shown by the indentation Different variables are used for the two loops, i and j, for clarity Other statements can be inside the outer loop, not just the inner loop

Nested while loops These work on the same principles as the for loops If they are controlled by counters, make sure the initializations of the counters are where they need to be. That is, if the inner loop needs to have its counter set to zero before the loop, you must decide whether the initialization needs to be inside the outer loop or outside the outer loop ct1 = 0 while ct1 < 5: ct2 = 0 while ct2 < 10: print(ct1, ct2) ct2 += 1 ct1 += 1

Data Validation while loops

Data validation Programs get input data from different sources All data should be ‘validated’ before the program tries to process it Depends on the specifications – what is valid data in your problem? May be general “numbers greater than zero” May be specific “only Y or N allowed”

What to do when invalid? What does your code do when invalid data is seen? Depends on the specification again Possible actions for invalid data stop the program (with explanatory error message, please!) give the user another chance to enter data (from the keyboard, probably) use a default value for the data and proceed as usual skip the bad data and proceed as usual (not always possible)

Using sentinel logic to validate keyboard input The requirement is that the user must enter Y or N or Q, nothing else Design ask the user for input while the input is NOT valid display an error message (with acceptable inputs shown) ask the user for input The trickiest part is the condition for the while while inp != ‘Y’ and inp != ‘N’ and inp != ‘Q’: is what you need. A common mistake is to use or instead of and If both cases of letters are allowed, it is simpler to change the input to one case, then test as above (remember the.upper and.lower methods)