Insight Through Computing 7. The While-Loop For-Loop Problems Introduce While-Loops.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Welcome to Who Wants to be a Millionaire
Arithmetic Calculations
Chapter 5: Control Structures II (Repetition)
Welcome to Who Wants to be a Millionaire
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
CMPT 120 Control Structures in Python
Summer 2012 Instructor: Hassan Khosravi
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Decisions If statements in C.
Java Math Class. What is the Math Class? The Math Class is another class that is prepared by Java for us to use We use this class for mathematical operations.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Header, Specification, Body Input Parameter List Output Parameter List
MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
3-2 What are relational operators and logical values? How to use the input and disp functions. Learn to use if, if-else and else-if conditional statements.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Example – calculating interest until the amount doubles using a for loop: will calculate up to 1000 years, if necessary if condition decides when to terminate.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
6. More on the For-Loop Using the Count Variable Developing For-Loop Solutions.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Introducing Loop Statements Liang, pages Loop statements control repeated execution of a block of statements Each time the statements in the block.
1 10/9/06CS150 Introduction to Computer Science 1 for Loops.
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
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
PHP flow of control & functions
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Understanding Randomness
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
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.
Review for Test #2 Rational Numbers and Irrational Numbers Real Numbers Powers and Exponents Scientific Notation.
CS1109 L AB 3 July 3rd. R OAD M AP Homework submission Review How to use function and scripts While-end Finish last exercise Lab 2 Challenge questions.
While Loops ENGR 1181 MATLAB 10.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
Computer Science I: Understand how to evaluate expressions with DIV and MOD Random Numbers Reading random code Writing random code Odds/evens/…
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
L6. More on the For-Loop Using the Count Variable Developing For-Loop Solutions.
Computer Programming 12 Lesson 6 – Loop structure By: Dan Lunney.
ALGORITHMS AND FLOWCHARTS
REPETITION CONTROL STRUCTURE
Python: Control Structures
While Loops in Python.
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Logical Operators and While Loops
Iteration: Beyond the Basic PERFORM
Let’s all Repeat Together
Logical Operators and While Loops
Another Example Problem
Matlab Basics.
Intro Math Problem Solving September 14
While Loops in Python.
REPETITION Why Repetition?
Presentation transcript:

Insight Through Computing 7. The While-Loop For-Loop Problems Introduce While-Loops

Insight Through Computing Problem Solving With the for-Loop The calculation to be repeated. end for count variable = expression for starting value expression for ending value :

Insight Through Computing Question Time How many lines of output are produced by the following script. A. 2 B. 50 C. 51 D. 101 for k=100:200 if rem(k,2)~=0 disp(‘k’); end

Insight Through Computing There is a line of output for every Odd number between 100 and 200. Answer = 50

Insight Through Computing for count variable = expression for starting value expression for ending value : For-Loop Shortcoming When you use a for-loop, you need to know the exact extent of the repetition.

Insight Through Computing OK for Many Situations Here is a typical for-loop Problem: Simulate the tossing of a fair coin 100 times and print the number of “Heads”

Insight Through Computing % Running sum… H = 0; for tosses = 1:100 r = rand; if r <.5 % Agree that this means “heads” H = H + 1; end fprintf(‘H = %2d\n’,H)

Insight Through Computing Not OK in Other Situations Simulate the game of “Gap10”: Toss a fair coin until | #Heads – #Tails | = 10 Score = number of required tosses The number of required tosses is not known in advance.

Insight Through Computing What We Need A loop that “shuts down’’ as soon as |H-T| = =10.

Insight Through Computing H = 0; T = 0; tosses = 0; while abs(H-T)<10 r = rand; tosses = tosses + 1; if r <.5 H = H + 1; else T = T + 1; end fprintf( … )

Insight Through Computing How a While-Loop Works Warm-up exercise: Any for-loop can be written as a while-loop.

Insight Through Computing A Simple For-loop s = 0; for k=1:5 s = s + k; fprintf(‘%2d %2d\n’,k,s)) end

Insight Through Computing The While-loop Equivalent k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end k s k and s are initialized

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 0 k 0 k 0 s 0 s Is k < 5 true? Yes. Execute the loop body.

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 1 k 1 k 1 s 1 s Is k < 5 true? Yes. Execute the loop body. 1 1

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 2 k 2 k 3 s 3 s Is k < 5 true? Yes. Execute the loop body

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 3 k 3 k 6 s 6 s Is k < 5 true? Yes. Execute the loop body

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 4 k 4 k 10 s Is k < 5 true? Yes. Execute the loop body

Insight Through Computing How it Works in Detail k = 0; s = 0; while k < 5 k = k + 1; s = s + k; fprintf(‘%2d %2d\n’,k,s) end 5 k 5 k 15 s Is k < 5 true? No, done with loop

Insight Through Computing A Modified Problem Print the smallest k so that … + k >= 30

Insight Through Computing How it Works in Detail k = 0; s = 0; while s < 30 k = k + 1; s = s + k; end fprintf(‘%2d %2d\n’,k,s) k s k and s are initialized

Insight Through Computing How it Works in Detail k = 0; s = 0; while s < 30 k = k + 1; s = s + k; end fprintf(‘%2d %2d\n’,k,s) 0 k 0 s 0 s Is s < 30 true? Yes. Execute loop body.

Insight Through Computing How it Works in Detail k = 0; s = 0; while s < 30 k = k + 1; s = s + k; end fprintf(‘%2d %2d\n’,k,s) 1 k 1 s 1 s Is s < 30 true? Yes. Execute loop body.

Insight Through Computing Defining Variables k = 0; s = 0; while s < 30 %s is the sum 1+ … + k k = k + 1; s = s + k; end This “property” is true all during the loop

Insight Through Computing Spotting a While Situation InnerA = (n/2) sin(2  /n)Outer A = n tan(  /n) As n increases, InnerA and OuterA approach pi, the area of the unit circle. When will |OuterA – InnerA| <= ?

Insight Through Computing PseudoCode Development Repeat while |OuterA – InnerA| > Increase n Update InnerA Update OuterA Identify the repetition and a criteria that says “keep iterating”.

Insight Through Computing PseudoCode Development n = 3; InnerA = area of inscribed triangle OuterA = area of the circumscribed triangle Repeat while |OuterA – InnerA| > Increase n Update InnerA Update OuterA The “players” have to be initialized

Insight Through Computing PseudoCode Development n = 3; InnerA = area of inscribed triangle OuterA = area of the circumscribed triangle Repeat while |OuterA – InnerA| > Increase n Update InnerA Update OuterA Print n What to do after loop terminates.

Insight Through Computing Pattern for doing something an Indefinite number of times % Initialization while ( not-stopping signal ) % do something % update status (variables) end

Insight Through Computing Question Time What is the last line of output produced by this script? A. 1 B. 2 C. 4 D. 16 E. I dunno n = 5 while n>1 disp(‘I dunno’) if rem(n,2)==0 n = n/2 else n = 3*n+1 end

Insight Through Computing Two More While Examples Each motivated by the limitations of the for-loop

Insight Through Computing Example 1: Up/Down Sequence Pick a random whole number between one and a million. Call the number n and repeat this process: if n is even, replace n by n/2. if n is odd, replace n by 3n+1 Does it ever take more than 1000 updates to reach one?

Insight Through Computing Aside: Random Integers How do we generate a random integer from an interval? n = ceil( *rand)

Insight Through Computing Need the Built-In Function ceil afloor(a)ceil(a) floor : next smallest integer ceil : next biggest integer

Insight Through Computing Random Integers % x is random real, 0 < x < 1 x = rand % y is random real, 0 < y < 10^6 y = *x % n is rand integer from 1,…,10^6 n = ceil(y) n = ceil( *rand)

Insight Through Computing The Central Repetition: if rem(n,2)==0 n = n/2; else n = 3*n+1 end Note cycling once n == 1: 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, …

Insight Through Computing Shuts Down When n==1.. step = 0; while n > 1 if rem(n,2)==0 n = n/2; else n = 3*n + 1; end step = step+1; fprintf(' %4d %7d\n',step,n) end

Insight Through Computing Cycles after n ==1 for step = 1:1000 if rem(n,2)==0 n = n/2; else n = 3*n + 1; end fprintf(' %4d %7d\n',step,n) end

Insight Through Computing Example 2: Square Roots Pick a random number x between one and a million. Compute the sqrt(x) by L = x; W = 1; Repeat until relative error in L <= 10^-15: L = (L+W)/2; W = x/L; Print relative error in L

Insight Through Computing Shuts Down After Convergence s = sqrt(x); L = x; W = 1; k = 0; while k==0 || relErr > 10^-15 k = k+1; L = (L+W)/2; W = x/L; relError = abs(L-s)/s end

Insight Through Computing Shuts Down After Convergence s = sqrt(x); L = x; W = 1; k = 0; while k==0 || relErr > 10^-15 k = k+1; L = (L+W)/2; W = x/L; relError = abs(L-s)/s end Error: relErr not initialized when the while Loop is entered.

Insight Through Computing Shuts Down After Convergence s = sqrt(x); L = x; W = 1; k = 0; while k==0 || relErr > 10^-15 k = k+1; L = (L+W)/2; W = x/L; relError = abs(L-s)/s end During the first check of the condition, k==0 is true. Matlab doesn’t bother to check the relErr comparison since the or is true. No prob that relErr uninitialized

Insight Through Computing Nested Loop Problem On average, how many coin tosses are there in a game of Gap10? Estimate by simulating 10,000 games.

Insight Through Computing PseudoCode sum = 0 for k=1:10000 Simulate a game of Gap10 and assign to the variable tosses the number of required tosses. sum = sum + tosses; end p = sum/10000

Insight Through Computing H = 0; T = 0; tosses = 0; while abs(H-T)<10 r = rand; tosses = tosses + 1; if r <.5 H = H + 1; else T = T + 1; end