C — Variables and integer arithmetic
C integer division gives the whole quotient and the remainder operator gives what is left. For 125 nonnegative cents, dividing by 100 separates 1 dollar from 25 cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
#include <stdio.h>
int main(void) {
int n = 2;
n++;
printf("%d\n", n);
}
3
Calculate a receipt in cents
Declare price_cents as const int and quantity as int. Division of nonnegative integers gives the whole-dollar part. The percent operator gives the remaining cents. Choose a wider type and check bounds if a real order could exceed INT_MAX.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
C17. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 lesson.c -o lesson
./lesson
#include <stdio.h>
int main(void) {
const int price_cents = 125;
int quantity = 3;
int total = price_cents * quantity + 50;
printf("%d.%02d\n", total / 100, total % 100);
return 0;
}
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.