Section 22.4 While Loops - While vs Until
While loops are most useful when we don’t have a set list of items to repeat over or any time we can more easily describe “here is the sign we should stop” rather than “here are all the values we need to do this for”. We saw one example of that in the program that asked for user input. But there are many other situations in which a while
is the easiest way to make a loop.
Say we want to convert a decimal number to binary using the division method. The
divide by two method says that we need to keep dividing by 2
until the quotient is 0. That is a description of when to stop, which means a while loop is what we will use to write the algorithm. However, when we write a while loop, we need to describe the conditions required to
“keep doing the loop”. If we want to
“stop when the quotient is 0” that is the same as
“keep going while the quotient is NOT 0.” Try running this version of the algorithm in codelens mode:
Checkpoint 22.4.2.
We have a program that is going to keep adding interest to a bank account until the balance
reaches $10,000 or more. Which would be the correct logic to complete while ___________:
?
while balance >= 10000
That is the "until" logic - the situation to stop in. We want the condition under which to continue.
while balance < 10000
Correct. The sign to keep going is that the balance is less than 10000
while balance == 10000
We need to write the logic that describes when to continue looping. That would only loop if we already had 10000.
while balance != 10000
That is close. We need to loop until we hit 10000. But if we do not hit 10000 exactly, that loop would not stop.
Thus a while loop allows us to write a program to use Newton’s method to calculate a square root and say “keep repeating the formula until the answer stays the same”. This will produce the most accurate answer we can produce, without having to worry in advance about how many repetitions we should ask for. Try running this program and changing number
to smaller and larger values. Notice how the number of repetitions is different for different numbers.
You have attempted
of
activities on this page.