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.

Therefore, the loop will continue to execute infinitely.

2. Consider the following while loop, write a for loops that generates the same output?

j = 10
while j >= 5 :
print("X")
j = j - 1
for j in range(10, 5, -1):
print("X")
  1. range(10, 5, -1):
  • This creates a range starting from 10 (inclusive) down to 6 (exclusive) with a step of -1. It’s essentially equivalent to [10, 9, 8, 7, 6].

2. for j in range(10, 5, -1):

  • This initiates a for loop that iterates over each element in the range generated by range(10, 5, -1).

3. In each iteration of the loop:

  • The variable j takes the value of the current element in the range, starting from 10 and decrementing by 1 in each iteration.
  • Inside the loop body, print("X") is executed, which…

--

--