edited by
5,501 views
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;
    }
}
  1. $40$
  2. $41$
  3. $42$
  4. $43$
edited by

5 Answers

Best answer
23 votes
23 votes

Correct answer is (C) $42$

It will start comparison from $(85, 5), (84, 6), (83, 7),\ldots,(45, 45), (44, 46)$

Hence, total number of comparison will be $\mathbf{(85-44) + 1 = 41 + 1 = 42}$

edited by
15 votes
15 votes
After each comparison, i's value decrements by one and n's value increments by one.

'Initial value of i=85 and n=5

Let's assume that after x number of comparisons i and n will be equal.

hence, 85-x=5+x => x=40  after 40 comparisons i=n, So, 41st comparison will be successful as well, Now at 42nd comparison while loop condition will fail and execution will come out of while loop. Hence Total number of comparisons= 42
9 votes
9 votes
i= 85 , 84, 83, 82,81,..............

n= 5,6,7,8,9,.............................

difference= 80,78,76,74,.......0( our loop will stop only when i becomes less than n )

In the series 80,78,76,74,.......0 , No of terms = 80/2+1 =41

Value of i=85-41=44

value of n=5+41=46

Hence at 42nd iteration loop will stop and make total 42 comparisions.
2 votes
2 votes
Consider two APs:

${a_n}$=85,84,...... for i's

${b_n}$=5,6,7...... for n's

Here take ${a_n}$=${b_n}$ then we get $n=42$ (using ${a_n}$$=a+(n-1)*d$)

${a_{42}}$=44, ${b_{42}}$=46 So i became less than n, take the previous i and n ($a_{41}$=45,$b_{41}$=45)

At this point $i==n$ and one more iteration(comparison) to exit loop. So total comparison is $41+1=42$
Answer:

Related questions

4 votes
4 votes
2 answers
1