StreakPeaked· Practice

ExamsGATETechnical

Consider the following segment of C code: ```c int j, n; j = 1; while (j <= n) j = j * 2; ``` The number of comparisons made in the execution of the loop for any $n>0$ is:

  1. $\lfloor \log_2 n \rfloor + 1$
  2. $n$
  3. $\lfloor \log_2 n \rfloor$
  4. $\lfloor \log_2 n \rfloor + 1$

Correct answer: $\lfloor \log_2 n \rfloor + 1$

Solution

Starting from 1, $j$ takes values $1,2,4,\dots$ until it becomes greater than $n$. The number of successful iterations is $\lfloor \log_2 n \rfloor + 1$ for $n>0$, and the condition is checked one extra time after the final iteration, matching the same count in the given options.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →