C Arithmetic Operators
Arithmetic operators let you perform everyday math in your programs: addition, subtraction, multiplication, division, and finding a remainder. If you know basic math, you already understand most of these symbols. C only adds one you may not have seen before, the modulus operator.
The Arithmetic Operators
There are five arithmetic operators in C. Four of them behave exactly as you would expect from a calculator, while the fifth, the percent sign, gives you the remainder of a division.
Basic arithmetic
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Sum: %d\n", a + b);
printf("Difference: %d\n", a - b);
printf("Product: %d\n", a * b);
return 0;
}Integer Division and Modulus
When you divide two integers in C, the result is also an integer and any fractional part is thrown away. So 10 / 3 gives 3, not 3.33. The modulus operator % gives you what is left over from that division, which is very handy for checking if a number is even or odd.
Division and remainder
#include <stdio.h>
int main() {
int total = 17;
int groups = 5;
printf("Each group gets: %d\n", total / groups);
printf("Left over: %d\n", total % groups);
return 0;
}This program prints: Each group gets: 3 and Left over: 2. That is because 5 goes into 17 three times (15), leaving 2 behind.
- Integer division drops the fractional part.
- The % operator returns the remainder of a division.
- n % 2 equals 0 when n is even, and 1 when n is odd.