Doing Maths

The maths operators

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23 (!)
%Remainder7 % 21
#include <stdio.h>

int main() {
    int a = 7;
    int b = 2;
    printf("%d + %d = %d\n", a, b, a + b);
    printf("%d - %d = %d\n", a, b, a - b);
    printf("%d * %d = %d\n", a, b, a * b);
    printf("%d / %d = %d\n", a, b, a / b);
    printf("%d %% %d = %d\n", a, b, a % b);
    return 0;
}

Output

7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3
7 % 2 = 1

Whole-number division

Look at 7 / 2. It gives 3, not 3.5! When you divide two ints, C gives you an int back and throws away the decimal part.

To get the exact answer, at least one of the numbers must be a decimal:

#include <stdio.h>

int main() {
    printf("%d\n", 7 / 2);
    printf("%.1f\n", 7.0 / 2);
    printf("%.1f\n", 7 / 2.0);
    return 0;
}

Output

3
3.5
3.5

Think of it like this: Integer division is like sharing 7 sweets between 2 children: each child gets 3, and 1 sweet is left over. / tells you the 3, and % tells you the 1 left over.

The remainder operator %

% gives what is left over after dividing. It is surprisingly useful:

  • n % 2 is 0 when n is even, 1 when it is odd.
  • n % 10 is the last digit of n.
  • minutes % 60 is the minutes left after taking out the full hours.
#include <stdio.h>

int main() {
    int total = 135;
    printf("%d minutes = %d hours and %d minutes\n", total, total / 60, total % 60);
    printf("Last digit of 4827: %d\n", 4827 % 10);
    return 0;
}

Output

135 minutes = 2 hours and 15 minutes
Last digit of 4827: 7

Order of operations

Like in school maths, *, / and % happen before + and -. Use brackets to change the order:

#include <stdio.h>

int main() {
    printf("%d\n", 2 + 3 * 4);
    printf("%d\n", (2 + 3) * 4);
    return 0;
}

Output

14
20

Common mistake: Dividing by zero. x / 0 with whole numbers crashes the program. Always make sure you never divide by 0.

HOME LABS COMMUNITY DASHBOARD