Whole-Number Division

Division in C has a catch. Try to guess what this statement prints:

printf("%d\n", 7 / 2);

This prints:

3

Not 3.5, but 3. When you divide two whole numbers, the result is a whole number too: C throws away the decimal part. It doesn't round, it just cuts it off, so 19 / 10 is 1, and 2 / 3 is 0. This is called integer division.

It works like division with a remainder from primary school: how many times one number fits into another. The remainder is given by the % operator (programmers call it modulo):

printf("%d\n", 7 / 2);
printf("%d\n", 7 % 2);
printf("%d\n", 10 % 5);

This prints:

3
1
0

Two fits into seven three times (3 × 2 = 6), and 1 is left over. When the division works out exactly, the remainder is 0. That's how you can tell even numbers from odd ones: an even number divided by two leaves a remainder of 0, an odd number leaves 1.

Don't mix up the two jobs of the % sign. Inside the format string, it starts a format specifier, such as %d. Outside the quotes, between two numbers, it calculates the remainder. In printf("%d\n", 7 % 2);, the first % is part of %d, and the second one calculates.

Integer division is handy, for example, for time. 135 minutes is 2 hours (135 / 60) and 15 minutes (135 % 60):

int minutes = 135;
printf("%d h %d min\n", minutes / 60, minutes % 60);

This prints:

2 h 15 min

% works only with whole numbers. With a double, such as 7.5 % 2, the program doesn't compile, and the compiler reports invalid operands to binary expression ('double' and 'int'). The operands are the values on both sides of an operator, and a double doesn't fit %.

Instructions

Four friends ordered pizzas, cut into 18 slices altogether. How many whole slices does each of them get? Calculate it from the variables and print:

Slices each: 4

How many slices are left over? Calculate it with % and print it on the next line:

Slices left: 2

The pizzeria says that the delivery takes 75 minutes. Below, create a variable delivery of type int with the value 75, and print it in hours and minutes, calculated with / and %:

Delivery in 1 h 15 min

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/11