How many times is the comparison i ≥ n performed in the following program? int…

2022

How many times is the comparison i ≥ n performed in the following program? int i = 200, n = 110; main() { while (i ≥ n) { i = i - 1; n = n + 1; } }

  1. A.

    46

  2. B.

    47

  3. C.

    48

  4. D.

    90

Attempted by 518 students.

Show answer & explanation

Correct answer: B

image.png

Short answer: 47 comparisons.

  • Initial values: i = 200, n = 110 → difference (gap) = i - n = 90.

  • Each iteration decreases i by 1 and increases n by 1, so the gap decreases by 2 each iteration.

  • After m iterations the gap = 90 - 2m. The loop runs while i ≥ n, i.e., while gap ≥ 0. Find smallest m with gap < 0: 90 - 2m < 0 ⇒ m > 45, so the smallest integer m = 46. Therefore the loop executes 46 iterations.

  • The condition i ≥ n is evaluated once before each iteration and one final time when it fails. Total comparisons = iterations + 1 = 46 + 1 = 47.

Conclusion: The comparison i ≥ n is performed 47 times.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Up Lt Grade Assistant Teacher 2025