Consider the following C code: #include <math.h> void main() { double pi =…

2013

Consider the following C code:

#include <math.h>
void main()
{
 double pi = 3.1415926535;
 int a = 1;
 int i;
 for(i=0; i < 3; i++)
 if(a = cos(pi * i/2) )
 printf("%d ",1);
 else printf("%d ", 0);
}

What would the program print?

  1. A.

    000

  2. B.

    010

  3. C.

    101

  4. D.

    111

Attempted by 559 students.

Show answer & explanation

Correct answer: C

Concept

  • An unbraced loop or if/else governs exactly ONE statement. A complete if/else is itself a single statement, so a for loop with no braces legally controls the entire if/else as its single body.

  • In a condition, '=' is ASSIGNMENT, not comparison. if(a = expr) stores expr into a and then tests a's value; any non-zero result is true, zero is false.

  • Assigning a double to an int variable TRUNCATES toward zero (drops the fractional part); the int's value, not the original double, is what gets tested.

Applying it

Here a is an int, so cos(...) is truncated to an int before the truthiness test. The loop runs for i = 0, 1, 2:

  1. i = 0: cos(0) = 1.0 -> a = 1 -> non-zero (true) -> prints 1

  2. i = 1: cos(pi/2) is a tiny value near zero (pi is slightly less than the true value, so it is about 0.00000000004, not exactly 0) -> truncated to int 0 -> zero (false) -> prints 0

  3. i = 2: cos(pi) = -1.0 -> a = -1 -> non-zero (true) -> prints 1

Cross-check

Note the catch at i = 1: the double result is not literally 0, yet because a is an int the fractional value is truncated to 0, which is what makes the test false. Concatenating the three printed digits with spaces gives the output 1 0 1, i.e. 101.

Explore the full course: Isro