While Loops!
Goals:
- Learn about while loops, an alternative to for loops for interation.
Coding Snippets:
Math and Computer Concepts:
while
loops continue to iterate so long as the specified boolean condition evaluates totrue
. They are particularly useful when the required number of iterations is not known (or even knowable) in advance of running the script. This is true of both examples above, owing to the use of therandom
function.while
loops check the specified condition before each iteration, so it is possible that the code inside the while block won't ever run.while
loops are more flexible thanfor
loops: anything that can be done with afor
loop can be done with awhile
loop.
Activities:
Save each of the following in a folder called WhileLoops.
- WhileLucky: Copy one of the LuckyStreak programs (from ConditionalLogic or Text folders) and modify it to use a
while
loop, rather than afor
loop withbreak
. - Write a script that creates ConcentricRings (circles within circles), using
while
. Start with the biggest circle, and then make the radius of each successive circle smaller, stopping when you reach a minimum size (such as 1). - After you make one set of concentric rings, put that code inside a for loop to make a cool ConcentricRingsDesign.
- Write a program that tracks how many rolls it takes to RollDoubles. Make your program more interesting by graphically showing the result of each roll and reporting the final number of rolls with labels.
- EstimateSqrt2: The sides an isosceles right triangle (one with a 90° and two 45° angles) have the proportions \(\small{1:1:\sqrt{2}}\). Use this fact to compute an estimate for the square root of two, by measuring how many units the turtle has to move to go from one 45° angle to another, and dividing this by the length of the other legs. Compare your result to JavaScript's estimate of the root of 2,
sqrt(2)
.