Counting with a While Loop

It’s easy to have the computer repeat something a specific number of times. We have done this with a for loop and a list of numbers created with the range function as shown below.

Activity: CodeLens 1 (for_counter_8_3)

We can also do it with a while loop.

For example, we could have a computer count up from 1 to 10. We will use a counter variable that we will increment inside the loop. Increment means increase the value by one. Note that we continue the loop as long as the counter is less than the desired last value plus one.

Activity: CodeLens 2 (while_count)

Side by Side Comparison of a For Loop and a While Loop

Let’s look at these loops side by side. The first line in the for loop creates the variable counter and the list of values from 1 to 10. It then sets counter equal to 1 and executes the body of the loop. In the body of the loop it prints the current value of counter and then changes counter to the next value in the list.

The first line of the while loop creates the variable counter and sets its value to 1. The second line tests if the value of counter is less than 11 and if so it executes the body of the loop. The body of the loop prints the current value of counter and then increments the value of counter. The loop will stop repeating when counter is equal to 11.

a for loop next to an equivalent while loop

Figure 1: A for loop and the equivalent while loop

Which is the best loop to use when you want to execute a loop a known number of times? Which way uses less code or seems less error prone? The problem with using a while loop to repeat code a specific number of times is that you may forget to change the value that you are testing inside the body of the loop and in that case you will have an infinite loop.

The following code is an attempt to show another way to print the values from 1 to 10. However, it currently has an error and is an infinite loop. Fix the code below so that it isn’t an infinite loop.

Use a while loop to count from 5 to 9. Print the current value in the counter at every interation in the loop.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page