Skip to content

Division and remainder

Read · 1 of 5

int / int throws away the decimals

When both sides are ints, / gives a whole-number answer: 17 / 5 is 3, not 3.4. The part after the point is dropped.

% gives the remainder: 17 % 5 is 2. Together they split a number: n % 10 is the last digit of n, and n / 10 is everything before it.

Read this lesson as text

Why 7 / 2 is 3 in C, and how % gives you the remainder.

int / int throws away the decimals

When both sides are ints, / gives a whole-number answer: 17 / 5 is 3, not 3.4. The part after the point is dropped.

% gives the remainder: 17 % 5 is 2. Together they split a number: n % 10 is the last digit of n, and n / 10 is everything before it.

Taking a number apart

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    int last = n % 10;
    int rest = n / 10;
    printf("last %d, rest %d\n", last, rest);
    return 0;
}
  1. Line 5: n is 4831.
  2. Line 6: 4831 divided by 10 leaves remainder 1: the last digit.
  3. Line 7: 4831 / 10 is 483.1, and int division drops the .1.
  4. Line 8: Printed.

Integer maths

#include <stdio.h>

int main() {
    printf("%d %d %d\n", 7 / 2, 7 % 2, 2 / 7);
    return 0;
}

What does this print?

  • 3 1 0
  • 3.5 1 0.28
  • 3 1 2
Show the answer

3 1 0 7 / 2 is 3 (decimals dropped), the remainder is 1, and 2 / 7 is 0.

Exercise: Minutes to hours

Read a number of minutes and print it as hours and minutes: 125 → 2 h 5 min.

Exercise: First and last digit of a 3-digit number

Read a 3-digit number and print its first digit and its last digit, separated by a space: 472 → 4 2.