② Six code-reading questions
Execute the code mentally before choosing an answer. Read the explanation even if you get it wrong.
Q1. Integer division
printf("%d\n", 17 / 5);
What is the output?
3.4
3
4 (rounding)
3.400000
Explanation: Both operands are integers, so 17 / 5 gives 3: the fractional part is discarded, not rounded to nearest. Use 17.0 / 5 or (double)17 / 5 for floating-point division.
Q2. Floating-point division with a cast
int a = 17, b = 5;
printf("%f\n", (double)a / b);
What is the output?
3.000000
3.400000
3
Compilation error
Explanation: The cast converts a to double before division. 17.0 / 5 is 3.4, printed as 3.400000 with %f. The expression (double)a / b means ((double)a) / b.
Q3. Testing with remainder (%)
int n = 17;
printf("%d %d\n", n / 5, n % 5);
What is the output?
3 2
3.4 0
3 5
2 3
Explanation: 17 / 5 is the integer quotient 3, and 17 % 5 is the remainder 2, satisfying 17 = 5 × 3 + 2. Remainder is useful for divisibility tests such as n % 2 == 0.
Q4. Compound assignment
int a = 10;
a += 5;
a *= 2;
printf("%d\n", a);
What is the output?
25
30
20
15
Explanation: Initially a=10. a += 5 makes it 15; a *= 2 makes it 30. The output is 30.
Q5. Postfix increment
int x = 5;
int y = x++;
printf("x=%d y=%d\n", x, y);
What is the output?
x=5 y=6
x=6 y=5
x=6 y=6
x=5 y=5
Explanation: Postfix x++ supplies the old value 5 to y, then increments x to 6. The output is 5 6. Prefix ++x would increment first, making both values 6.
Q6. Operator precedence
printf("%d\n", 2 + 3 * 4);
What is the output?
20
14
9
24
Explanation: Multiplication has higher precedence than addition. First compute 3 × 4 = 12, then 2 + 12 = 14. To obtain 20, write (2 + 3) * 4.