Consider the following 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?
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 from to (initial values: i = 0, count = 0):
- : Since
j >= 0is false, the right operandi++is not evaluated.iremains , andcountremains . - :
j >= 0is true.i++is evaluated. The post-increment returns the current value ofi(, which is false) and then incrementsito . Since the condition is false,countremains . - :
j >= 0is true.i++is evaluated. It returns (true) and incrementsito . The condition is true, socount = 0 + 1 = 1. - :
j >= 0is true.i++is evaluated. It returns (true) and incrementsito . The condition is true, socount = 1 + 2 = 3. - :
j >= 0is true.i++is evaluated. It returns (true) and incrementsito . The condition is true, socount = 3 + 3 = 6.
After exiting the loop, the final values are i = 4 and count = 6.
The statement count = count + i executes:
Thus, the program compiles successfully and outputs 10.
Free practice · Your answers on this page are not saved.
