Learn C · lesson 3 of 60 · about 7 minutes
Arithmetic and Integer Division
Convert bytes, KiB and MiB with + - * / %, and predict when division throws the decimals away.
What you'll learn
- Use the arithmetic operators
- Predict integer division
- Use % for remainders
Bytes, KiB and MiB
Computers count in bytes. 1024 bytes make a KiB, and 1024 KiB make a MiB. Converting between them is arithmetic: C has + - * / %.
When both sides of / are ints, C does integer division: the answer is a whole number and the rest is thrown away. 2560 / 1024 is 2, not 2.5. % gives what was thrown away, the remainder: 2560 % 1024 is 512.
Whole MiB and what's left over
#include <stdio.h>
int main(void) {
int kib = 2560;
printf("%d MiB\n", kib / 1024);
printf("%d KiB left over\n", kib % 1024);
printf("%d bytes\n", kib * 1024);
return 0;
}Output
2 MiB
512 KiB left over
2621440 bytesWhy whole numbers?
The processor has separate circuits for whole numbers and for decimals. Whole-number division is exact, with no rounding errors, and it's what you want for counting things: blocks on a disk, items in a list.
When you do want the decimals, make one side a double: 2560 / 1024.0 is 2.5. Storing the answer in a double afterwards is too late, because the division has already happened.
What's worked out first
#include <stdio.h>
int main(void) {
printf("%d %d\n", 2 + 3 * 4, (2 + 3) * 4);
return 0;
}Output
14 20Tip
*, / and % happen before + and -. Use brackets when you want a different order.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.