Module 9: Loops: the while loop | CMSC 105 Elementary Programming - Fall 2024

Module 9: Loops: the while loop

Note: Create a text file called module9.txt where you will store you answers to exercise questions. The questions that are not related to changing code. You will submit this file on Blackboard along with your code.

Objectives

By the end of this module you will be able to:

While loops: an example

The numbers 1, 4, 9, 16, 25, and so on are squares, with the next one being 36 (which is 62).

The program:

k = 1
while k * k < 1000:
    k = k + 1

# Reduce by 1 because now k * k > 1000
k = k - 1

print('largest square < 1000:', k * k, '= square of', k)

Exercise 1: Type up the above in my_while_example.py.


How does a while-loop work?

Thus, as long as the value of k is such that k * k is less than 1000, execution enters and stays inside the loop.

Let’s examine a simpler while-loop:

k = 1
while k < 6:
    print(k)
    k = k + 1

Exercise 2: Trace this program by drawing and filling out a tracing table that shows the values that will be stored in memory and the output value. Take a picture of the tracing table that you created attach it to Blackboard as while2.png.Then confirm by typing up the above in my_while_example2.py.


Exercise 3: Consider this variation:

k = 7
while k < 6:
    print(k)
    k = k + 1

Trace this program by drawing and filling out a tracing table that shows the values that will be stored in memory and the output value. Take a picture of the tracing table that you created attach it to Blackboard as while3.png. Then confirm by typing up the above in my_while_example3.py.


Exercise4: Consider this variation:

k = 1
while k < 6:
    print(k)

Trace the first 10 steps of this program by drawing and filling out a tracing table that shows the values that will be stored in memory and the output value. Take a picture of the tracing table that you created attach it to Blackboard as while4.png. Then confirm by typing up the above in my_while_example4.py. After a minute, you may need to terminate the execution of the program by hand (by clicking the “STOP” button).


Keep in mind:

While loops: an example with floating point variables

Consider this example:

x = 0.5
s = 0
while s <= 2:
    s = s + x

print('s =', s)

Exercise 5: Try to guess the output before confirming in my_while_example5.py.


Note:

Let’s look at a more illustrative version now:

x = 0.5
s = 0
k = 0
while s <= 2:
    s = s + x
    k = k + 1

print('s =', s, 'k =', k)

Here, we’ve added a counter variable to track each loop iteration.


Exercise 6: Trace this program by drawing and filling out a tracing table that shows the values that will be stored in memory and the output value. Take a picture of the tracing table that you created attach it to Blackboard as while6.png. Then confirm in my_while_example6.py.


So far it’s been straightforward. Let’s now solve a problem:

x = 1
s = 0
k = 0
while s < 0.9:
    x = x / 2   # Halve x each time
    s = s + x
    k = k +1

print(k)

Exercise 7: Trace this program by drawing and filling out a tracing table that shows the values that will be stored in memory and the output value. Take a picture of the tracing table that you created attach it to Blackboard as while7.png. Then confirm in my_while_example7.py.


A few comments that go beyond the scope of the course (just for curiosity):

for vs. while

Let’s contrast for-loops and while-loops by writing a for-loop as a while-loop, and vice-versa.

As an example, let’s print the numbers 0 through 10:

# for-loop version
for k in range(11):
    print(k)

# while-loop version
k = 0
while k < 11:
    print(k)
    k = k + 1

Note:


Exercise 8: Consider this for-loop:

for k in range(5, 20, 2):
    print(k)

In my_for_while.py, write the while-loop equivalent.


Next, let’s go from while to for:

Note:


Exercise 9: Write and test both loops in my_for_while2.py.


Using break in loops

Let’s return to our first example of finding the last square that’s less than 1000.

Recall what we wrote:

k = 1
while k*k < 1000:
    k = k + 1

k = k - 1
print('largest square < 1000:', k*k, '= square of', k)
for k in range(1, 50):
    # print('Before-if: k =', k)
    if k*k > 50:
        break
    # print('After-if: k =', k)

k = k - 1
print(k)

Exercise 10: Type up the above in my_break.py, removing the # to un-comment the two print statements, so that you can see exactly what happens when the if-condition triggers.


Let’s point out:


Exercise 11: The type it up in my_break2.py, to confirm.


Next, let’s look at a while-loop version of the original

Observe:

k = 1
# The condition is set to run forever,
# and instead rely on the if-condition 
# to break out
while True:
    if k*k > 50:
        # When the break executes,
        # we jump right out of the loop
        # to whatever code follows the loop
        break
    k = k + 1

# This code is after the loop
k = k - 1
print(k)

Exercise 12: In your module9.txt, describe what would go wrong if the statement k = k + 1 was mistakenly typed in as k = k - 1.


Loops within loops

Just as we’ve seen nested for-loops, so can we have nested while-loops or one kind inside another.

Consider this example:

m = 10
while m <= 10000:
    for k in range(1, m):
        if (k + 1) * (k + 1) >= m:
            print('largest square <', m, ':', k * k)
            break
    m = m * 10

Exercise 13: Type the above in my_nested_loop.py and try to make sense of it.


Let’s explain:


Exercise 14: In my_nested_loop2.py, change the inner loop to a while loop so that we get the same output.


Exercise 15: In my_nested_loop3.py, change the code so that both the outer loop and inner loop are for-loops. One way to solve this problem: use a variable called j to range through the outer for-loop and then ensure that the inner loop executes only when j happens to equal m. (Aren’t you glad we have while-loops?)