Looping Through Complexity: 36 Loop Problems to Practice Solving

btd
37 min readFeb 1, 2024
Photo by Li Zhang on Unsplash

1. How many times does the following loop run?

i = 0
j = 1
while j >= 1 :
print("" , i , ";" , j)
i = j + 1
if i % 2 == 0 :
j = j - 1
2 times
  1. Initialization:
  • i is initialized to 0.
  • j is initialized to 1.

2. Iteration 1:

  • j is greater than or equal to 1, so the loop executes.
  • The values of i and j are printed.
  • i is updated to the value of j + 1, which is 2.
  • Since i % 2 == 0 (2 is divisible by 2), j is decremented by 1, becoming 0.
  • End of iteration.

3. Iteration 2:

  • j is now 0, which is not greater than or equal to 1, so the loop terminates.

Therefore, the loop runs for 2 iterations.

2. What does the following code compute?

sum = 0
count = 0
value = input("enter an integer")
while value > 0 :
sum = sum + value
count = count + 1
value = input("enter next integer")
result = sum * 1.0 / count
print(result)
The code computes the average of all the positive…

--

--