CSci 157 - Loop Worksheet


For each code example below, do the following:
  1. Circle and label each of the initialization, test, and update (label with I, T, and U). If any of these parts are missing, say so.

  2. Determine what value(s) of the loop variable(s) will make the loop terminate.

  3. Determine how many times the loop body will be executed. If one of I, T, or U are missing, write down indeterminate.  If the loop will never terminate, write down infinite loop.

  4. What is the output or result of executing each code fragment? Be as specific as you can; sometimes nothing is the appropriate answer.
    When you cannot say exactly what the output will be, describe the output you expect.

Number 1: correctly accumulate and output a sum? 
i = 0
sum = 0
x = 3

while i < 5:
sum = sum + x
i = i + 1

print("Sum = ", sum)

Number 2: properly print the first 20 multiples of 5?

x = 5
i = 1


while i > 20:
print( i*x )

i = i-1

Number 3: does it print 'Hello' 4 times?
MAX = 4
j = 0

while j < MAX:
print("Hello!")
Number 4: assuming graphics.py has been imported, what does this do?
win = graphics.GraphWin("Example", 200, 200)
h = win.getHeight()/2
w = win.getWidth()/4
while w > 10 and h > 20:
w_double = w * 2
if h > height:
print("h is too high: ", h)
else:

ln = graphics.Line(graphics.Point(w, h), graphics.Point(
w_double, h))
ln.draw(win)
h = h +
w_double

w = w - 10
h = h - 10

Number 5: correctly accumulate a sum of numbers entered by the user? (like, tallying the total cost of items scanned at check-out)
i = 0
sum = 0.0

x = float(input("Enter a value, or zero if nothing to enter: ")
more = (x != 0)

while more:
sum = sum + x
i = i + 1
x = float(input("Enter another value, or zero if no more to enter: ")
more = (x != 0)

print(str(i) + " items with total cost ", sum)

# NOTE the number of times loop iterates is dependent on user input, so assume values entered are: 0.5, 1.5, 3, 5, 17, 0
Number 6: does it print some number of 'Lower!' strings?
for _ in range(1, 50, -2):
print("Lower!")

Number 7: correctly accumulate a sum from values in a range?
sum = 0
MIN = 16

for k in range(20, MIN, -1):
x = k * 10
print(x)
sum = sum + x

print("\t Sum = ", sum)
Number 8: consider calling the function hailstone(5), what is output?
## hailstone : int -> int
def hailstone(seed):
   "Generates the hailstone sequence; seed must be >= 1"
 
   print(f'Starting value: {seed}')
   onetime = True
 
   while onetime:
      if seed % 2 == 1:
         seed = seed * 3 + 1
      else:
         seed = seedint // 2
      print(f'Next value = {seed}')
      onetime = seed != 1
   return seed