Mastering Loop Logic: 30 Loop Problems to Practice Solving

btd
21 min readJan 31, 2024

1. How many times does the following loop execute?

i = 0
found = False
while i < 100 and found != True :
i = i + 1
print(i, end = " ")
j = i * i
if i * i * i % j == j :
found = True
An infinite number of time
  1. Initially, i is set to 0, and found is set to False.
  2. The loop condition i < 100 and found != True checks two conditions: whether i is less than 100 and whether found is not equal to True.
  3. Inside the loop, i is incremented by 1 in each iteration (i = i + 1).
  4. Then, j is calculated as the square of i.
  5. The if condition if i * i * i % j == j is checked. This condition will always be true because i * i * i is always divisible by j (which is i * i).
  6. As a result, found is set to True.
  7. However, since the loop condition checks both i < 100 and found != True, and i is incremented in each iteration, i will eventually reach a value greater than or equal to 100, but the loop will continue to execute because the condition found != True remains true due to found being set to True only after the if condition inside the loop.

--

--