in Algorithms edited by
433 views
0 votes
0 votes

How many times is the comparison $i >= n$ performed in the following program?

 int i = 200 n = 80;
main()
 {
  while (i >= n)
   {
     i = i - 2
     n = n + 1
   }
 }



 

in Algorithms edited by
433 views

1 Answer

5 votes
5 votes
Best answer

so initially we checked condition (200>=80) and it passed  then from next time onwards we are decreasing i by 2 and increasing n by 1 and then comparing

so assume after first comparison we run this loop k times and then we get i =n

so,

200-2-2-2…..k times = 80+1+1+1…...k times

200-2k= 80+k

3k=120

k=40

 

so,

initially we checked for i=200 and n=80 and it passed

then we keep on checking till i=120 and n=120 (which means we checked for k=40 more times)

after 40th time i became 118 and n became 121

then we checked 1 more time and this time loop failed because 118>=121 is not true.
 

so total this condition i>=n is checked for 42 times.

selected by

Related questions