Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

While loops.
CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
CS0004: Introduction to Programming Repetition – Do Loops.
Computer Science 1620 Loops.
Chapter 5: Control Structures II (Repetition)
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©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.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
5.05 Apply Looping Structures
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Fundamentals of Python: From First Programs Through Data Structures
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
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.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10.
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Chapter 4 Introduction to Control Statements
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Chapter 7: The Repetition Structure Introduction to Programming with C++ Fourth Edition.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Making Choices with if Statements
Lecture 7: Repeating a Known Number of Times
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
Chapter 5: Control Structures II
JavaScript: Control Statements.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
3. Decision Structures Rocky K. C. Chang 19 September 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Computer Science Core Concepts
Adding Intelligence Check for the presence or absence of a condition in the environment Take the appropriate actions Involves making a choice (to do or.
Another Example Problem
Fundamentals of Python: First Programs Second Edition
Presentation transcript:

Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops

Another Example Problem Sir Isaac Newton developed a method to approximate the value of the square root of a given number. Suppose x is the number and guess is an approximation of the square root of x. Then a closer approximation to the actual square root of x is equal to (guess + x / guess) / 2 The initial value of guess is x / 2 y = x

Try Some Guesses Out in the Shell >>> from math import sqrt >>> x = 2 >>> sqrt(x) >>> guess = x / 2 >>> guess 1.0 >>> guess = (guess + x / guess) / 2 >>> guess 1.5 >>> guess = (guess + x / guess) / 2 >>> guess >>>

Use a Loop to Repeatedly Guess The approximation algorithm repeatedly replaces a guess with a better approximation. Write a program that allows the user to specify the value of x and the number of iterations used in this approximation. The program computes and displays the resulting estimate of the square root of x, as well as Python’s own estimate using Python’s math.sqrt function.

Use a for Loop import math x = float(input("Enter a number: ")) count = int(input("Enter the number of iterations: ")) guess = x / 2 for i in range(count): guess = (guess + x / guess) / 2 print("Guess: %f Actual: %f" % (guess, math.sqrt(x))) We perform a definite number of approximations

Or Use a while Loop import math x = float(input("Enter a number: ")) count = int(input("Enter the number of iterations: ")) guess = x / 2 i = 1 while i <= count: guess = (guess + x / guess) / 2 i = i + 1 print("Guess: %f Actual: %f" % (guess, math.sqrt(x))) This loop is also count-controlled, and is equivalent in meaning to the for loop

Syntax of the while Loop while : … A Boolean expression can be a comparison of two numbers or strings, using ==, !=,, = These operations return the Boolean values True or False Note that == means equal to, whereas = means assignment loop header loop body

Behavior of the while Loop Loop body Boolean expression False True while : # The condition # The loop body

Logic of the while Loop i = 1 while i <= count: guess = (guess + x / guess) / 2 i = i + 1 Before the loop header, the loop control variable must be set to the appropriate initial value Somewhere in the loop body, a statement must reset the loop control variable so that the Boolean expression eventually becomes False, to terminate the loop These steps were automatic in the for loop loop control variable

Extended Assignment x = x + 1 The increment of a variable, such as x += 1 is so common that Python includes some shorthand for it i = 1 while i <= count: guess = (guess + x / guess) / 2 i += 1

Any Arithmetic Operation x = x + 1x += 1 x = x - 1x -= 1 x = x * 2x *= 2 x = x / 2x /= 2

Which Loop Should I Use? A for loop works well when the number of iterations is predictable (usually count-controlled) A while loop works well when the number of iterations is not predictable How could the # of iterations be unpredictable?

Another Way to Look at Newton’s Method We repeatedly improve the guess until the difference between the square of the guess and x reaches a given tolerance value. tolerance = while |guess 2 - x| > tolerance guess = (guess + x / guess) / 2 We cannot predict how many times this process will be repeated This is called an indefinite loop or a conditional iteration

The while Loop import math x = float(input("Enter a number: ")) tolerance = guess = x / 2 while abs(guess ** 2 - x) > tolerance: guess = (guess + x / guess) / 2 print("Guess: %f Actual: %f" % (guess, math.sqrt(x))) Add a tolerance value and end the loop when the condition becomes false

Sentinel-Controlled Loops An indefinite loop can test for the presence of a special value called a sentinel When the sentinel is reached, the loop should stop

An Example Problem Input test scores from the user and print the average score. The user signals the end of input by simply pressing the enter or return key. This value shows up as an empty string, which is the sentinel value.

Sentinel-Controlled Loops sum = 0 count = 0 data = input("Enter a score or just return to quit ") while data != "": sum += int(data) count += 1 data = input("Enter a score or just return to quit ") if count == 0: print("No scores were entered") else: print("The average is", sum / count) The input statement must be written twice

Simplify with a break Statement sum = 0 count = 0 while True: data = input("Enter a score or just return to quit ") if data == "": break sum += int(data) count += 1 if count == 0: print("No scores were entered") else: print("The average is", sum / count) break causes an immediate exit from the enclosing loop

When Should I Use a break ? When the loop body executes at least once but the number of iterations is unpredictable The condition of the enclosing while loop is just True The condition for loop exit is placed in an enclosing if statement A break may also be helpful within a for loop, but more on that at a later date...

Input Checking redux rate = int(input('Enter the interest rate[0-100]: ')) if rate 100: print('ERROR: Rate must be between 0 and 100!') else: interest = principal * rate / 100 print('Your interest is', interest) We need to continue this process until the user enters a legitimate number

Input Checking redux while True: rate = int(input('Enter the interest rate[0-100]: ')) if rate 100: print('ERROR: Rate must be between 0 and 100!') else: break interest = principal * rate / 100 print('Your interest is', interest) The loop controls the input process The computation process occurs only after the loop has finished

For Monday Start Chapter 4