Consider the following segment of C-code:
int j, n;
j = 1;
while (j <= n)
j = j * 2;
The number of comparisons made in the execution of the loop for any is:
View worked solution
Answer: D
To find the total number of comparisons made by the while loop, we trace the values of at each step:
- Initially, .
- In each iteration, is doubled: .
The loop condition is . The loop terminates as soon as . Let be the number of successful iterations. For these iterations, the condition holds true:
Taking the base-2 logarithm:
Thus, there are successful comparisons where the loop body executes. After these, one final comparison is made where , which evaluates to false and terminates the loop.
Therefore, the total number of comparisons is:
Note: In the original GATE 2007 paper, Option D was printed as . The in the question text is a typographical error, and Option D is the intended correct choice.
Free practice · Your answers on this page are not saved.
