In C, which of the following statements sets y to 5 if x has the value 3, but…

2010

In C, which of the following statements sets y to 5 if x has the value 3, but not otherwise?

Answer: D. if (x == 3) y = 5;ConceptConcept: In C, an if statement evaluates the expression inside parentheses. The controlled statement runs only when that expression has a nonzero…

  1. A.

    if (x = 3) y = 5;

  2. B.

    if x == 3 (y = 5);

  3. C.

    if (x == 3); y = 5;

  4. D.

    if (x == 3) y = 5;

Attempted by 101 students.

Show answer & explanation

Correct answer: D

Concept

Concept: In C, an if statement evaluates the expression inside parentheses. The controlled statement runs only when that expression has a nonzero value.

The equality operator == compares two values, whereas the assignment operator = stores a value. A semicolon immediately after if ends the controlled statement.

Application

  1. Begin with x = 3.

  2. In if (x == 3) y = 5;, the comparison x == 3 evaluates to 1 (true).

  3. Because the condition is nonzero, the controlled assignment y = 5 runs. For any x other than 3, the comparison evaluates to 0 and the assignment is skipped.

Contrast

  • if (x = 3) y = 5; assigns 3 to x; the resulting nonzero value makes the body run regardless of the previous value of x.

  • if x == 3 (y = 5); does not use the required parentheses around the if condition in C.

  • if (x == 3); y = 5; places an empty statement after if, so y = 5 is outside the conditional body.

  • if (x == 3) y = 5; uses a parenthesized comparison and makes y = 5 the controlled statement.

Cross-check

Cross-check: With x = 4, x == 3 evaluates to 0, so y is unchanged. This confirms that y is set to 5 only when x equals 3.

Therefore, the required statement is if (x == 3) y = 5;.

Explore the full course: Tpsc Assistant Technical Officer

Loading lesson…