Computer Science
Is the loop in the code below infinite? How do you know (for sure) before you run it?
m = 3
n = 5
while n < 10:
m = n - 1
n = 2 * n - m
print(n, m)
Python Funda
34 Likes
Answer
The loop is not infinite. To know this without running it we can analyze how n is changed inside the loop in the following way:
n = 2 * n - m
Substituting value of m from m = n - 1,
n = 2 * n - (n - 1)
⇒ n = 2 * n - n + 1
⇒ n = 2n - n + 1
⇒ n = n + 1
Therefore, inside the loop n is incremented by 1 in each iteration. Loop condition is n < 10 and initial value of n is 5. So after 5 iterations, n will become 10 and the loop will terminate.
Answered By
14 Likes
Related Questions
How many times will the following for loop execute and what's the output?
for i in range(1,3,1): for j in range(i+1): print('*')
Find and write the output of the following python code:
for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] : print (Name) if Name[0] == 'T' : break else : print ('Finished!') print ('Got it!')
Write a program to print one of the words negative, zero, or positive, according to whether variable x is less than zero, zero, or greater than zero, respectively
Write a program that returns True if the input number is an even number, False otherwise.