Lesson 39 +10 XP

Arithmetic Operators

Arithmetic Operators

Arithmetic operators do the math: +, -, *, /, and %.

The five operators

  • + adds.
  • - subtracts.
  • * multiplies.
  • / divides.
  • % gives the remainder of a division.

A small program

#include <stdio.h>

int main() {
  int x = 10;
  int y = 3;
  printf("%d\n", x + y);   // 13
  printf("%d\n", x - y);   // 7
  printf("%d\n", x * y);   // 30
  printf("%d\n", x / y);   // 3
  printf("%d\n", x % y);   // 1
  return 0;
}

Integer division truncates

When both numbers are whole numbers (int), the result is a whole number. 10 / 3 is not 3.33; it is 3.

printf("%d\n", 10 / 3);       // 3
printf("%f\n", 10.0 / 3);     // about 3.333333

The remainder is left over

10 % 3 is 1: after putting two whole 3s into 10, there is 1 left over.

TL;DR

  • Arithmetic operators: +, -, *, /, %.
  • Integer divided by integer truncates the decimals.
  • Use a double to preserve a decimal result.
  • % gives the remainder, not the quotient.