Step 1 of 6
Arithmetic
C has the arithmetic operators you know: + (add), - (subtract), * (multiply) and / (divide). An expression combines values, variables and operators, and C works out (evaluates) its value.
#include <stdio.h>
int main(void) {
int a = 12 * 3 + 4;
int b = 12 * (3 + 4);
int c = 20 - 5 - 3;
printf("%d %d %d\n", a, b, c);
return 0;
}
40 84 12
Order of operations
C follows the same rules as school math. This order is called precedence:
- Parentheses first.
- Then
*,/and%(which you'll meet soon). - Then
+and-.
When operators have the same precedence, they go left to right: 20 - 5 - 3 is (20 - 5) - 3, which is 12, not 20 - (5 - 3).
So 12 * 3 + 4 multiplies first (36) and then adds (40). If you want the addition first, add parentheses. When you're not sure, add parentheses anyway: they cost nothing and make the intent obvious to the next reader.
Using variables in expressions
Expressions can mix numbers and variables. price * quantity + shipping reads the current values of the variables at the moment the line runs.
Your turn: make the program print Damage: 96 by filling in the operators. Base damage is 30, the multiplier is 4, armor absorbs 24.