Consider the following C program. #include <stdio.h> int main() { int i, j,…

2021

Consider the following 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;
 }

  1. A.

    The program will not compile successfully.

  2. B.

    The program will compile successfully and output 10 when executed.

  3. C.

    The program will compile successfully and output 8 when executed.

  4. D.

    The program will compile successfully and output 13 when executed.

Attempted by 268 students.

Show answer & explanation

Correct answer: B

Key insight: the logical AND expression (j >= 0) && (i++) uses short-circuit evaluation, so i++ is executed only when j >= 0. The i++ expression returns the previous value of i (then increments i), which affects whether the if-body runs.

  1. Initial values: i = 0, count = 0.

  2. For j = -3, -2, -1: j >= 0 is false, so i++ is not evaluated; i stays 0 and count remains 0.

  3. For j = 0: j >= 0 is true, so i++ is evaluated. i++ returns 0 (making the if condition false) but increments i to 1. count stays 0.

  4. For j = 1: i++ returns 1 and i becomes 2. The if condition is true, so count += 1 -> count = 1.

  5. For j = 2: i++ returns 2 and i becomes 3. The if condition is true, so count += 2 -> count = 3.

  6. For j = 3: i++ returns 3 and i becomes 4. The if condition is true, so count += 3 -> count = 6.

  7. After the loop: i = 4 and count = 6. The statement count = count + i makes count = 6 + 4 = 10.

Answer: The program prints 10.

Explore the full course: Gate Guidance By Sanchit Sir