Question

Consider the following ANSI C program.

#include <stdio.h>
int main()
{
    int i, j, count;
    count = 0;
    i = 0;
    for (j = -3; j <= 3; j++)
    {
        if ((j >= 0) && (i++))
            count = count + j;
    }
    count = count + i;
    printf("%d", count);
    return 0;
}

Which one of the following options is correct?

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2021 answer key

Solution

Trace the loop while carefully applying short-circuit evaluation of the logical AND operator and post-increment side effects.

Initially, count = 0 and i = 0. The loop runs for j=−3,−2,−1,0,1,2,3j = -3, -2, -1, 0, 1, 2, 3.

In C, (j >= 0) && (i++) evaluates left-to-right with short-circuiting:

  • j=−3j = -3: j >= 0 is false (0). The right operand (i++) is not evaluated. i remains 0.
  • j=−2j = -2: j >= 0 is false. i remains 0.
  • j=−1j = -1: j >= 0 is false. i remains 0.
  • j=0j = 0: j >= 0 is true (1). Right operand (i++) evaluates to the current value of i, which is 0 (false), and then i increments to 1. Because the condition evaluates to false, count = count + j does not execute.
  • j=1j = 1: j >= 0 is true. (i++) evaluates to 1 (true) and i becomes 2. Since condition is true, count = count + j = 0 + 1 = 1.
  • j=2j = 2: j >= 0 is true. (i++) evaluates to 2 (true) and i becomes 3. count = count + j = 1 + 2 = 3.
  • j=3j = 3: j >= 0 is true. (i++) evaluates to 3 (true) and i becomes 4. count = count + j = 3 + 3 = 6.

After the loop finishes, count = count + i = 6 + 4 = 10. The statement printf("%d", count); outputs 10, matching option B.

Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2021 Computer Science and Information Technology (CS, Set-1)
Question
47 of 65, printed as CS Q.37
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.