MCQ
Q.
Consider the following C++ code snippet:
int x = 15;
int y = 4;
int z = 2;
int result = x + y * z / 2;What will be the final value of the variable result?
Correct Answer: A
The correct answer is 19.
🔑 Key Points
- C++ follows standard operator precedence rules (BODMAS/PEMDAS). Multiplication (
*) and Division (/) have higher precedence than Addition (+) and Subtraction (-). - When operators have the same precedence (e.g.,
*and/, or+and-), they are evaluated from left to right. - Let's break down the expression
x + y * z / 2withx = 15,y = 4,z = 2: - First,
y * zis calculated:4 * 2 = 8. - Next,
8 / 2is calculated (left-to-right with multiplication):8 / 2 = 4. - Finally,
x + 4is calculated:15 + 4 = 19.
📄 Additional Information
- The order of precedence for common arithmetic operators is:
1. Parentheses()
2. Multiplication*, Division/, Modulo%(evaluated left-to-right)
3. Addition+, Subtraction-(evaluated left-to-right) - Understanding operator precedence is crucial for writing correct C++ logic and avoiding unexpected results. Using parentheses
()can explicitly control the order of evaluation if the default precedence is not desired or to improve readability. For example,(x + y) * z / 2would yield a different result.