Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loop Structures.

Similar presentations


Presentation on theme: "Loop Structures."— Presentation transcript:

1 Loop Structures

2 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 for more details

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

4 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) ?

5 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 ?

6 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;

7 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

8 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.

9 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:

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

11 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.

12 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

13 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

14 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++

15 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

16 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?

17 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.

18 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)]);

19 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

20 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

21 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?

22 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)

23 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

24 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

25 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

26 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

27 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)

28 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');

29 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, …

30 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');

31 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.


Download ppt "Loop Structures."

Similar presentations


Ads by Google