Lesson 7 of 7 · C Foundations · 2 min read · Updated

Operators and arithmetic

Doing sums — and the integer division trap that catches everyone once.

C has the arithmetic you expect: +, -, *, /. It also has %, the remainder operator, which is more useful than it looks.

c
int a = 17, b = 5;

printf("%d\n", a + b);   /* 22 */
printf("%d\n", a - b);   /* 12 */
printf("%d\n", a * b);   /* 85 */
printf("%d\n", a / b);   /* 3  — not 3.4 */
printf("%d\n", a % b);   /* 2  — the remainder */

The integer division trap

17 / 5 gives 3, not 3.4. When both sides are integers, C does integer division and throws the remainder away. It does not round — it truncates, so 19 / 5 is also 3.

To get 3.4, at least one side must be a floating-point number.

c
int a = 17, b = 5;

printf("%d\n",   a / b);            /* 3    */
printf("%.2f\n", 17.0 / 5);         /* 3.40 */
printf("%.2f\n", (float) a / b);    /* 3.40 */

Note

(float) a is a cast: it tells C to treat a as a float for this one calculation. The variable itself is unchanged.

What % is actually for

  • Is a number even? n % 2 == 0.
  • Every third item? i % 3 == 0.
  • Last digit of a number? n % 10.
  • Wrap a value into a range, such as hours on a clock: h % 12.

Shorthand you will see everywhere

c
int n = 10;

n += 5;   /* same as n = n + 5;  now 15 */
n -= 3;   /* now 12 */
n *= 2;   /* now 24 */
n++;      /* now 25 */
n--;      /* now 24 */

What does printf("%d", 7 / 2); print?

Try this now

  1. Write a program that reads a number of minutes and prints it as hours and minutes. / and % are all you need.
  2. Read two numbers and print their average to two decimal places. Watch out for the integer division trap.

Create a free account to save your progress, or sign in.