Skip to content
Official PYQ · 2021

GATE CS 2021 Set 1 Q37 — Programming in C

Explain with AI

​​​​​Consider the following ANSI C\text{ 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
View worked solution

Answer: B

The program uses the logical AND operator (&&), which exhibits short-circuit evaluation. In the expression (j >= 0) && (i++), the right-hand side (i++) is evaluated only if the left-hand side (j >= 0) is true.

Let's trace the loop for jj from −3-3 to 33 (initial values: i = 0, count = 0):

  • j=−3,−2,−1j = -3, -2, -1: Since j >= 0 is false, the right operand i++ is not evaluated. i remains 00, and count remains 00.
  • j=0j = 0: j >= 0 is true. i++ is evaluated. The post-increment returns the current value of i (00, which is false) and then increments i to 11. Since the condition is false, count remains 00.
  • j=1j = 1: j >= 0 is true. i++ is evaluated. It returns 11 (true) and increments i to 22. The condition is true, so count = 0 + 1 = 1.
  • j=2j = 2: j >= 0 is true. i++ is evaluated. It returns 22 (true) and increments i to 33. The condition is true, so count = 1 + 2 = 3.
  • j=3j = 3: j >= 0 is true. i++ is evaluated. It returns 33 (true) and increments i to 44. The condition is true, so count = 3 + 3 = 6.

After exiting the loop, the final values are i = 4 and count = 6.
The statement count = count + i executes:
count=6+4=10\text{count} = 6 + 4 = 10

Thus, the program compiles successfully and outputs 10.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions