Member-only story
Mastering Loop Logic: 30 Loop Problems to Practice Solving
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 = TrueAn infinite number of time- Initially,
iis set to 0, andfoundis set to False. - The loop condition
i < 100 and found != Truechecks two conditions: whetheriis less than 100 and whetherfoundis not equal to True. - Inside the loop,
iis incremented by 1 in each iteration (i = i + 1). - Then,
jis calculated as the square ofi. - The if condition
if i * i * i % j == jis checked. This condition will always be true becausei * i * iis always divisible byj(which isi * i). - As a result,
foundis set to True. - However, since the loop condition checks both
i < 100andfound != True, andiis incremented in each iteration,iwill eventually reach a value greater than or equal to 100, but the loop will continue to execute because the conditionfound != Trueremains true due tofoundbeing set to True only after the if condition inside the loop.
