Which one of the following will set the value of y to 5 if x has the value 3, but not otherwise ?
The condition must compare x with 3 using the equality operator ==, and y = 5 must be the body of the if, as in if (x == 3) y = 5. Writing if (x = 3) assigns 3 to x; that…
Choose your answer
Which one of the following will set the value of y to 5 if x has the value 3, but not otherwise ?
Answer and explanation
Correct answer D
The condition must compare x with 3 using the equality operator ==, and y = 5 must be the body of the if, as in if (x == 3) y = 5. Writing if (x = 3) assigns 3 to x; that value is non-zero, so y becomes 5 whatever x was before. A semicolon straight after the condition gives the if an empty body, so y = 5 then runs every time, and a condition without parentheses is a syntax error in C.
Practice for these exams
-
UGC NET Computer Science and Applications