Two kinds of division in C — Aptitude Question
Two kinds of division in C: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this C program print?
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("%d %.1f", a / b, (float) a / b);
return 0;
}Options
- 3 3.5
- 3 3.0
- 3.5 3.5
- 4 3.5
Show the answer and the worked solution
Correct answer: A. 3 3.5
Worked solution
- In a / b both operands are int, so C performs integer division: 7 / 2 = 3, with the fraction discarded rather than rounded.
- In (float) a / b the cast applies to a first, so the division is done in floating point: 7.0 / 2 = 3.5.
- The two conversion specifiers print 3 and 3.5 respectively, so the output is 3 3.5.
Answer: 3 3.5.
The idea
In C the operand types decide the operation, not the type of the variable you assign to. Casting one operand is enough, because the other is promoted to match it.
Shortcut. The first specifier is %d, so it prints an integer, and C truncates 3.5 to 3, not 4; the cast binds before /, so the second value is a true 3.5.
Common trap. "3 3.0" applies the cast after the division, as (float)(a / b); the cast outranks /, so 7 is converted first and the division keeps its .5.
All Programming Fundamentals questions · placement mock tests