Question:medium

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? 
 

Show Hint

In C, logical AND (&&) uses short-circuit evaluation, so the second operand is evaluated only if the first is true.
Updated On: Jan 30, 2026
  • The program will not compile successfully.
  • The program will compile successfully and output 10 when executed.
  • The program will compile successfully and output 8 when executed.
  • The program will compile successfully and output 13 when executed.
Show Solution

The Correct Option is B

Solution and Explanation

Step 1: Initialize variables.
Initially,

i = 0,   count = 0

The loop executes for values of j from −3 to 3.


Step 2: Analyze the conditional expression.
The condition used inside the loop is:

(j ≥ 0) && (i++)

The logical AND operator (&&) follows short-circuit evaluation. Hence, the expression i++ is evaluated only when j ≥ 0 is true.


Step 3: Evaluate each loop iteration.

For j = −3, −2, −1:
j ≥ 0 is false ⇒ i++ is not executed
i = 0, count = 0

For j = 0:
j ≥ 0 is true, i++ evaluates to 0 (false)
Condition fails, but i is incremented
i = 1, count = 0

For j = 1:
i++ evaluates to 1 (true)
count = count + 1 = 1
i = 2

For j = 2:
i++ evaluates to 2 (true)
count = 1 + 2 = 3
i = 3

For j = 3:
i++ evaluates to 3 (true)
count = 3 + 3 = 6
i = 4


Step 4: Final calculation.
After exiting the loop:

count = count + i = 6 + 4 = 10


Final Conclusion:
The program compiles successfully and prints:
10

Final Answer: (B)

Was this answer helpful?
0