Ravi and Rupali are asked to write a program to sum the rows of a 2×2 matrix…

Ravi and Rupali are asked to write a program to sum the rows of a 2×2 matrix stored in the array A.

Ravi writes the following code (Code A):

for n = 0 to 1
    sumRow1[n] = A[n][1] + A[n][2]
end

Rupali writes the following code (Code B):

sumRow1[0] = A[0][1] + A[0][2]
sumRow1[1] = A[1][1] + A[1][2]

Comment upon these two codes (assume the compiler performs no loop unrolling):

Answer: B. Code B will execute faster than Code AConcept: a loop pays a one-time cost to initialize its counter, then a recurring cost EVERY iteration — comparing the counter against the loop bound,…

  1. A.

    Code A will execute faster than Code B

  2. B.

    Code B will execute faster than Code A

  3. C.

    Code A is logically incorrect.

  4. D.

    Code B is logically incorrect.

Attempted by 4 students.

Show answer & explanation

Correct answer: B

Concept: a loop pays a one-time cost to initialize its counter, then a recurring cost EVERY iteration — comparing the counter against the loop bound, executing the body, incrementing the counter, and branching back to the top — before it can exit. Manually unrolling a loop (writing out every iteration's statements explicitly, with no loop construct) removes that recurring per-iteration compare/increment/branch overhead entirely, so it runs at least as fast as an equivalent loop, provided the compiler itself performs no automatic unrolling.

Application: trace both codes for this 2×2 matrix.

  1. Code A sets up a loop over n = 0 to 1. Before the body can run for n = 0, the loop must initialize n and compare it against the bound 1.

  2. For n = 0, Code A executes the body — sumRow1[0] = A[0][1] + A[0][2] — then increments n to 1 and re-compares it against the bound.

  3. For n = 1, Code A executes the body again — sumRow1[1] = A[1][1] + A[1][2] — then increments n to 2, compares again, and exits the loop.

  4. Code B contains exactly these two statements — sumRow1[0] = A[0][1] + A[0][2] and sumRow1[1] = A[1][1] + A[1][2] — with no counter to initialize, compare, increment, or branch on.

Cross-check: both codes perform the identical two additions and produce identical results, so neither is logically wrong — that rules out either code being called ‘logically incorrect’. The question also explicitly rules out the compiler performing automatic loop unrolling; if it did, the two would compile down to the same instructions and run equally fast. Since manually unrolling here removes real loop-control instructions that Code A must still execute, Code B completes the same work using strictly fewer instructions for this fixed, 2-iteration case.

Result: Code B executes faster than Code A.

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…