Home » Programming & Data Structure » Programming and data structure miscellaneous » Question

Programming and data structure miscellaneous

Programming & Data Structure

  1. 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 n > 0 is

    1. n

Correct Option: D

From the statement j = j*2 in the code we get to know that j increases in power of 2’s. Let us say that this statement execute x times then, according to the question for while loop
2^x < = n
Therefore, x < = log2 n
And also for termination of while loop there will be an extra comparison required. Thus, total number of comparisons = x + 1



Your comments will be displayed only after manual approval.