MCQ
Q.
Consider the following C++ code snippet:
#include
int main() {
int a = 5;
int b = 2;
int result = a / b;
std::cout << result << std::endl;
return 0;
}
What will be the output of this program?
Correct Answer: B
The correct answer is 2.
🔑 Key Points
- In C++, when both operands of the division operator
/are of an integer type, the division performed is integer division. - Integer division truncates any fractional part, effectively rounding down towards zero. For
5 / 2, the mathematical result is 2.5. - Since both
a(5) andb(2) are declared asint, the expressiona / bevaluates to2. - The integer result
2is then assigned to theintvariableresultand printed to the console.
📄 Additional Information
- If one or both operands of the division operator are of a floating-point type (e.g.,
floatordouble), then floating-point division is performed, yielding a result with decimal precision (e.g.,5.0 / 2would be2.5). - To achieve floating-point division with integer variables, one of the operands can be type-casted, for example,
static_cast, which would yield(a) / b 2.5. - Understanding operator precedence and type conversion rules is fundamental in C++ programming.