Lecture 7 - Exercises

7A - While Loops

  1. What does the following program print?

    count = 10
    while count < 21:
        print(count, end=" ")
        count += 3

Consider the following program:

n = 12345
m = 0
while n != 0:
    m = (10 * m) + (n % 10)
    n //= 10
  1. How many times is the body of the while loop executed?
  2. What are the values of m and n after the code is executed?

Consider the following code, which has two missing snippets, marked [[1]] and [[2]].

i = [[1]]
while [[2]]:
  i += 1
  print(i)

Consider the following candidates to replace the missing snippet [[1]]:

  1. 0

  2. 1

  3. 10

and the following candidates to replace missing snipped [[2]]:

  1. i < 9

  2. i <= 9

  3. i < 10

  4. i <= 10

To form a complete program, we need to pick a pair of snippets, one to replace [[1]] and one to replace [[2]].

  1. Which pair or pairs of snippets will cause the program to print the numbers from 1 to 10, inclusive?
  2. Which pair or pairs of snippets will cause the program to print exactly 10 numbers?

7B - Nested while loops

Consider the following program:

i = 0
while i < 4:
  j = 1
  while j < 11:
    print('*', end='')
    j += 1
  i += 1
  print()
  1. How many asterisks (*) are printed by the program?
  2. What are the values of i and j at the end of the program?