The GATE Grind

GATE 2021 CS – Question 47

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

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?

  1. The program will not compile successfully.
  2. The program will compile successfully and output 10 when executed.
  3. The program will compile successfully and output 8 when executed.
  4. The program will compile successfully and output 13 when executed.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (B) The program will compile successfully and output 10 when executed.

Explanation

i++ runs only when j>=0. At j=0, i++ yields 0 (false) and i becomes 1. For j=1,2,3, i++ is true, so count = 1+2+3 = 6 and i ends at 4. Output = 6 + 4 = 10.