10.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 algorithm to do the conversion 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 situation that means “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:

Warning

The condition for a while loop always describes a test that tells us to keep going - “Keep doing this while”. A common mistake is to write until logic - a test that says when to stop.

If the natual way to say what you want involved until, like “Keep going until the user enters 0”, turn it into while by reversing it - “Keep going while the user has NOT entered 0”.

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