GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 15

Loop-condition comparison count

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2007 paper

GATE 2007, Q15 1 mark · MCQ
Report issue

Control Flow & Loop Tracing

Question 15, GATE 2007: Consider the C fragment:
int j, n;
j = 1;
while (j <= n)
    j = j * 2;
For n>0, how many comparisons are made during execution? The printed choices are below; note the distinction between successful comparisons and the final failing test.
Options:
(A) ceil(log₂ n)+1
(B) n
(C) ceil(log₂ n)
(D) floor(log₂ n)+1
Tap to enlarge
Your answer
Answer & solution

Answer: floor(log2 n)+2 including the final failed test; no exact listed option (no official key was published)

1. Approach. Let k=floor(log₂ n). The successful tests use j=20 through 2k. Then the loop tests 2k+1 once and fails. Check n=1 as a quick boundary example: two tests, one iteration.

2. Derivation and interpretation. Assume n is supplied positive and arithmetic does not overflow. The loop condition is tested with j=1,2,4,...,2^floor(log2 n), all successful, then once more at 2^(floor(log2 n)+1), which fails. Thus body executions and successful comparisons number floor(log2 n)+1, but all comparisons number floor(log2 n)+2. Option D counts successful tests/body executions only. The fragment declares n without assigning it; the question’s n>0 premise must supply its value, and literal fixed-width C may also overflow for large n. No official key is inferred.

Original paper, page 4