Loop Structures.

Slides:



Advertisements
Similar presentations
Create a Simple Game in Scratch
Advertisements

Create a Simple Game in Scratch
Nested If Statements While Loops
Lets Play Catch! Keeping Score in Alice By Francine Wolfe Duke University Professor Susan Rodger May 2010.
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
While Loops. Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right.
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.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Complexity (Running Time)
DCT 1123 PROBLEM SOLVING & ALGORITHMS INTRODUCTION TO PROGRAMMING.
MrsBillinghurst. net A2 Computing A2 Computing Projects Game Animation in Pascal.
Today in CS161 Lecture #4 Solving Problems with Computers Walk through the Tic Tac Toe Algorithm Getting ready for Creating Programs Turn the Inches to.
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
Control Structures FOR Statement Looping.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition.
Invitation to Computer Science, Java Version, Second Edition.
Chapter 2 - Algorithms and Design
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
 Make sure you are subscribed to announcements on Moodle.  Activity 4 will be due 48hrs after your lab ends.
By the end of this session you should be able to...
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
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.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Making Decisions uCode: October Review What are the differences between: o BlueJ o Java Computer objects represent some thing or idea in the real.
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.
For loops in programming Assumes you have seen assignment statements and print statements.
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.
Game Maker Terminology
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
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.
1 Project designed and created by M. Shajith Kumar.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Week 61 Introduction to Programming Ms. Knudtzon C Period Tuesday October 12.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Iteration. Iteration: Review  If you wanted to display all the numbers from 1 to 1000, you wouldn’t want to do this, would you? Start display 1 display.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
The Last Lecture CS 5010 Program Design Paradigms "Bootcamp" Lesson © Mitchell Wand, This work is licensed under a Creative Commons Attribution-NonCommercial.
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.
Objectives. Objective The purpose of this tutorial is to teach the viewer how to solve for the acceleration of each mass in a standard two- body pulley.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
Design Document Sample Given two concentrated circles with different radii, calculate the area which falls inside the big circle but outside the small.
Beginning Programming for Engineers Matlab Conditional Computation.
Conditionals.
Scratch Programming Cards
Manipulating Pictures, Arrays, and Loops part 2
Repetition Structures Chapter 9
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.
Using a Stack Chapter 6 introduces the stack data type.
Building Java Programs
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Using a Stack Chapter 6 introduces the stack data type.
Algorithm and Ambiguity
Conditional and iterative statements
Using a Stack Chapter 6 introduces the stack data type.
Using a Stack Chapter 6 introduces the stack data type.
Flowcharts and Pseudo Code
Nested If Statements While Loops
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.
A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 13 (Reed) - Conditional.
Software Development Techniques
Presentation transcript:

Loop Structures

PutPixel function Some of our examples will use the function putPixel, that turns on the pixel at location (x,y) In java, the origin is located at top left corner, and y-coordinate values increase as you go down, making all corrdinates on the screen have positive components Refer to www.bilkent.edu.tr/~ccelik/cs111/java_draw for more details

Draw a Line initWindow; putPixel(10,10,g); What if we need a line with length 200?

Draw a line of 200 pixels Maybe we need a new type of statement that will repeat things for a specified amount of times. Here is an attempt (in pseudo-code): 200 times do putPixel(?, 10) ?

Draw a line of 200 pixels (2) We need to change the x coordinate at each iteration. Otherwise we keep putting the pixels at the same location. How do we vary the x coordinate at each iteration ?

vary  variable Draw a line of 200 pixels (3) Let’s use a variable currentX that will pull the window under the sewing machine needle currentX=10; 200 times do putPixel(currentX, 10); currentX = currentX + 1;

Draw a line What if the user wants to specify the length of the line? Our loop (repetition) statement should be flexible enough to provide varying number of iterations : get the length of the line from user currentX = 10 for length times do putPixel(currentX, 10) currentX = currentX + 1

Mines? Let’s say that our drawing board has some “mines” on it. Our line explodes, or ends, when it hits a mine. We can ask if a particular pixel location has a mine by using the function “checkMine(x,y)” Now we don’t know how long our line will extend, we have to check at each step.

Checking for Mines We need a loop structure that checks a condition (here, the existence of mines, as well as the length of the line) at the beginning of each loop (iteration) It should only put pixels when our conditions are satisfied. How? Enter the “while” structure:

While loop While <cond> block 1 block 2 (rest of the program)

Condition ? what is the condition for putting a pixel to location (currentX,10) ? First, currentX - 10 should be less than the length Second, we need the location (currentX, 10) to be free of any mines. We need both conditions to hold.

Line drawing with mines get the length of the line from user currentX = 10 while (currentX - 10 < length && ~checkMine(currentX, 10) ) putPixel(currentX, 10) currentX = currentX + 1

General Line Drawing a = input('Enter the begining x-coordinate of your line '); b = input('Enter the ending x-coordinate of your line '); y = input('Enter the y-coordinate of your line'); currentX = a; while (currentX < b && ~checkMine(currentX,y, mines)) putPixel(currentX, y, g); currentX = currentX + 1; end

Some other solutions currentX=a While (currentX <= b) putPixel(currentX, b) currentX++ currentX=a While (currentX < b) putPixel(currentX, b) currentX++ putPixel(currentX (or b),y) putPixel(a,y) currentX=a + 1 While (currentX <= b) putPixel(currentX, b) currentX++ Delta = 0 While (delta <= (b-a)) putPixel(a+delta, b) delta++

NextPow2 example let’s compute nextpow2 ourselves In other words, find the first, or smallest c, such that 2^c >= n, for a given n. One solution is to try increasing values of c until the condition is reached

NextPow2 count = 0 while ~(2^count >= n) report count as the result count = count + 1 report count as the result Note that the condition is equivalent to : (2^count < n) this is a bad algorithm … why?

NextPow2 without taking powers Given a count, and 2^count, how de we compute 2^(count + 1) ? Use two variables to hold the count (needed to return the result) and the power (needed to decide when to stop.

NextPow2 Matlab Program count = 0; pow = 1; n = input('Input the number '); while (pow < n) % invariant : pow = 2^count count = count + 1; pow = pow * 2; end disp(['Result is ' num2str(count)]);

Number Guessing Game computer picks a random number btw. 1-10 the user have 3 chances to get it right if the user gets the number correctly in 3 tries, the program congratulates the user

Number Guessing Game the outline of a typical while loop : perform initializations while (condition) perform the repetitive step update the parameters of condition perform final adjustments

Repetitive Step get a guess from user What do we inside the loop? what is our condition for stopping? either user gets it right or he uses up his 3 tries in other words, what is our condition for continuing?

Current Algorithm count it using a variable (tries) perform initializations while (guess is not right and user had used less then 3 tries) get a guess from user update the parameters of condition perform final adjustments How do we know how many tries the user had? count it using a variable (tries)

Counting the Tries perform initializations while (guess is not right and user had used less then 3 tries) get a guess from user tries = tries + 1 perform final adjustments since we ask whether a guess is right, we need a guess before coming to the while loop we need to make sure the variable tries always gives the number of tries

Counting the Tries pick a random number x between 1 and 10 get a guess from user tries = 1 while (guess ~= x and tries < 3) tries = tries + 1 perform final adjustments now let’s look at what happens after the loop ends

Number Guessing Game the outline of the solution : pick a number get an initial guess while (guess is wrong but still have more chances) get the next guess update the number of tries display the result of the game initializations condition repetitive step & update condition params final adjustments

The Aftermath … What are the reasons we might have gone out of the loop? The condition must have failed : guess ~= x and tries < 3 that means, either : guess == x , or tries >= 3, meaning, tries == 3

The Aftermath … There are three distinct cases of going out the loop first condition is right, second is wrong second condition is right, first one is wrong both of the conditions are right guess == x, tries < 3 guess ~= x, tries == 3 guess == x, tries == 3 in cases 1 & 3, the user is successful : (guess == x)

The Matlab Program x = ceil(rand * 10); guess = input('Try to guess my number '); tries = 1; while (guess ~= x && tries < 3) tries = tries + 1; end if (guess == x) disp('You got it !'); else disp('Maybe some other time');

A Slight Variation How can we do it without getting the user input in two different lines? Hint: initialize variables so that you always enter the loop (by satisfying the condition) the first time. make sure guess ~= x by setting guess to something different than x, like -1, inf, x -1, x+1, …

Another variation x = ceil(rand * 10); tries = 0; guess = -1; while (guess ~= x && tries < 3) guess = input('Try to guess my number '); tries = tries + 1; end if (guess == x) disp('You got it !'); else disp('Maybe some other time');

Moral of the story … There are a number of ways to solve a problem The particular solution you reach may depend on the order you put the pieces of the puzzle If we had tackled the initialization before the condition, we might have reached to the second solution.