Precedence of Arithmetic Operators
The precedence of arithmetic operators determines the order in which operators are evaluated in an expression.
Here is the order of precedence for arithmetic operators:
Operator | Description | Precedence | Associativity |
---|---|---|---|
* | Multiplication | High | Left to Right |
/ | Division | High | Left to Right |
% | Modulus | High | Left to Right |
+ | Addition | Low | Left to Right |
- | Subtraction | Low | Left to Right |
Order of Evaluation
- Operators with higher precedence (
*
,/
,%
) are evaluated first. - Operators with the same precedence are evaluated based on associativity (left-to-right).
- Parentheses (
()
) can be used to explicitly specify the order of operations.
Example:1
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 15;
int result = a + b * c; // Multiplication is evaluated before addition
printf("Result: %d\n", result);
return 0;
}
Output
Result: 155
Example:2
#include <stdio.h>
int main() {
int result = (10 + 20) * (3 - 5) / 2;
printf("Result = %d\n", result);
return 0;
}
Output
Result = -30
Steps:
1.Add: 10 + 20 = 30
2.Subtract: 3 - 5 = -2
3.Multiply: 30 * -2 = -60
4.Divide: -60 / 2 = -30