Numbers & Math
7 min · C
Do math with int variables and the basic operators.
Enemy 1 of 5
Arithmetic operators and integer division
C gives you the four familiar operators: + - * / for addition, subtraction, multiplication and division, plus % for remainder (also called modulo). You can combine variables and numbers directly inside an expression, and normal order-of-operations rules apply — multiplication and division happen before addition and subtraction.
The sharpest gotcha in this lesson: dividing two ints in C always produces an int, so the fractional part is silently dropped. 7 / 2 gives you 3, not 3.5. If you need a precise decimal result you must use a floating-point type like double for at least one of the operands — this trips up nearly everyone the first time they meet it.
Once you have a result, print it the same way you learned last lesson: with %d as the placeholder inside printf, and the expression as the corresponding argument.
Loading editor...