loop structures. putpixel function some of our examples will use the function putpixel, that turns...
Post on 21-Dec-2015
216 views
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);putPixel(11, 10, g);putPixel(12, 10 , g);putPixel(13, 10 , g);putPixel(14, 10 , g);putPixel(15, 10 , g);putPixel(16, 10 , g);putPixel(17, 10 , g);
putPixel(18, 10 , g);
putPixel(19, 10 , g);
putPixel(20, 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 ?
Draw a line of 200 pixels (3)
• vary variable• 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)– 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
• What do we inside the loop?
get a guess from user
• 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
perform initializationswhile (guess is not right and user had used less then 3 tries)
get a guess from userupdate 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 initializationswhile (guess is not right and user had used less then 3 tries)
get a guess from usertries = 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 10get a guess from usertries = 1while (guess ~= x and tries < 3)
get a guess from usertries = 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
1. first condition is right, second is wrong2. second condition is right, first one is wrong3. both of the conditions are right
1. guess == x, tries < 32. guess ~= x, tries == 33. 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)
guess = input('Try to guess my number ');
tries = tries + 1;
end
if (guess == x)
disp('You got it !');
else
disp('Maybe some other time');
end
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;endif (guess == x) disp('You got it !');else disp('Maybe some other time');end
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.