Loading lessons...
Remainder and Odd/Even Check
Remainder and Odd/Even Checks
The remainder operator % is one of the most useful tricks in C.
The remainder operator
% gives what is left over after a division:
printf("%d\n", 7 % 2); // 1
printf("%d\n", 7 % 3); // 1
printf("%d\n", 12 % 6); // 0
The even-number check
x % 2 == 0 is true exactly when x is even:
int x = 8;
if (x % 2 == 0) {
printf("Even");
}
Quotient and remainder together
10 / 4 is the quotient (2) and 10 % 4 is the remainder (2). Together they cover everything a division leaves behind.
TL;DR
%gives the remainder of a division.- Check even numbers with
x % 2 == 0. - Quotient comes from
/, remainder from%. a % bis always 0 when b divides a evenly.