13 votes 13 votes How many times is the comparison $i \geq n$ performed in the following program? int i=85, n=5; main() { while (i >= n) { i=i-1; n=n+1; } } $40$ $41$ $42$ $43$ Algorithms cmi2015 algorithms time-complexity + – go_editor asked May 27, 2016 • edited Nov 7, 2019 by go_editor go_editor 5.7k views answer comment Share Follow See all 4 Comments See all 4 4 Comments reply Manu Thakur commented Dec 23, 2017 reply Follow Share We can re-write the code of while loop as follows while( i>=n) { i=i+2; } i=87, n=5; after 40 iterations value of i will be $85 - 40*2 = 5$. For 41st iteration, i>=n evaluates true, and i will become 3. for 42nd iteration i>=5 fails as 3 < 5. So, In total, 'while' condition is checked 42 times, which results 41 times in success and 1 time in failure. 2 votes 2 votes Nitesh Singh 2 commented Jan 4, 2019 i edited by Nitesh Singh 2 Nov 26, 2019 reply Follow Share the formula for this would be = $\left \lfloor \frac{x-y}{2} \right \rfloor +2$ addition of 2(1 for checking loop condition for false and 1 for including last integer) 0 votes 0 votes Aks9639 commented Sep 14, 2019 reply Follow Share i thought it slightly different way :- since i'm average student so i always do it in first go like this-> it is similar to without changing variable n like n = n+1 why we not do like step size of i = i - 2 then while(i >= n) { i = i - 2; // same step size decremented by 2 } then we got -> 85, 83 , 81 , 79........, 9, 7, 5, 3(terminate cond) n=5(no change) 85 = 3+(n-1)* 2// simple AP simply got n = 42. 1 votes 1 votes JashanArora commented Jan 6, 2020 reply Follow Share I mentally solved this is a weird way. Can someone verify if this approach is generally all right? i is moving towards n with a speed of 1. And n is moving towards i with a speed of 1, as well. Relative speed of i is, therefore, 2. So, to reach 5, i takes $\frac{85-5}{2}=40$ steps. When they're equal, it's a non-issue, so do +1. Now, they're unequal and the condition will be tested once more and it will fail. So, $40+1+1=42$ 0 votes 0 votes Please log in or register to add a comment.
1 votes 1 votes Answer: soujanyareddy13 answered May 6, 2021 soujanyareddy13 comment Share Follow See all 0 reply Please log in or register to add a comment.