Consider the following segment of C++ code. int j, n; for(j = 1; j <= n; ) j =…

2021

Consider the following segment of C++ code.

int j, n;

for(j = 1; j <= n; )

j = j * 2;

What is the number of comparisons made in the execution of the loop for any n > 0?

  1. A.

    n + 1

  2. B.

    (n + 1)/2

  3. C.

    log2(n + 1)

  4. D.

    log2 n + 1

Attempted by 248 students.

Show answer & explanation

Correct answer: D

Analysis of Loop Comparisons

The given C++ code segment is:

for(j = 1; j <= n; ) j = j * 2;

Let's trace the execution to count the number of comparisons made in the condition (j <= n).

Step-by-Step Execution

1. Initialization: j starts at 1.

2. Iteration 1: Check if 1 <= n. (Comparison 1). If true, j becomes 1 * 2 = 2.

3. Iteration 2: Check if 2 <= n. (Comparison 2). If true, j becomes 2 * 2 = 4.

4. Iteration 3: Check if 4 <= n. (Comparison 3). If true, j becomes 4 * 2 = 8.

In general, after k successful iterations, j becomes 2^k. The loop continues as long as 2^k <= n.

Calculating Total Comparisons

The loop terminates when j > n. Let the number of successful iterations be k. Then:

2^k <= n < 2^(k+1)

Taking log base 2 on both sides:

k <= log2(n) < k + 1

This implies k is the integer part of log2(n), or more precisely, the number of times we can double 1 before exceeding n is floor(log2(n)).

However, we must count the final comparison that fails. The loop performs a comparison for every iteration (including the one that fails).

If the loop runs k times successfully, it performs k successful comparisons and 1 final failed comparison.

Total comparisons = k + 1.

Since k is approximately log2(n), the total number of comparisons is log2(n) + 1.

Note: In discrete math contexts for this specific problem type, the answer is often expressed as log2(n) + 1, assuming n is a power of 2 or using ceiling/floor logic that results in this form.

Thus, the correct option is D: log2(n) + 1.

Explore the full course: Up Lt Grade Assistant Teacher 2025