C Arithmetic Operators: Beginner's Guide
In C programming, arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, division, and modulus.
Letβs walk through them with clear explanations and real code examples.
What Are Arithmetic Operators in C?
Arithmetic operators work on numeric data types (int
, float
, double
) to perform mathematical operations. These are some of the most frequently used operators in any program.
List of Arithmetic Operators
Operator | Name | Description | Example | Result |
---|---|---|---|---|
+ | Addition | Adds two values | 5 + 3 | 8 |
- | Subtraction | Subtracts right from left | 5 - 3 | 2 |
* | Multiplication | Multiplies two values | 5 * 3 | 15 |
/ | Division | Divides left by right | 5 / 2 | 2 (int) or 2.5 (float) |
% | Modulus | Returns remainder (integers only) | 5 % 2 | 1 |
Example Program: Arithmetic in C
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d + %d = %d\n", a, b, a + b);
printf("Subtraction: %d - %d = %d\n", a, b, a - b);
printf("Multiplication: %d * %d = %d\n", a, b, a * b);
printf("Division: %d / %d = %d\n", a, b, a / b);
printf("Modulus: %d %% %d = %d\n", a, b, a % b);
return 0;
}
β Output:
Addition: 10 + 3 = 13 Subtraction: 10 - 3 = 7 Multiplication: 10 * 3 = 30 Division: 10 / 3 = 3 Modulus: 10 % 3 = 1
π§ Note: For
int / int
, the result is also an integer. Use type casting for decimal division.
Example: Division with Type Casting
#include <stdio.h>
int main() {
int x = 5, y = 2;
float result = (float)x / y;
printf("Division (float): %.2f\n", result); // Output: 2.50
return 0;
}
β Best Practices
Tip | Reason |
---|---|
Use (float) for accurate division | Prevents integer truncation |
Avoid modulus with float types | % only works with integers |
Check divisor before division | Prevent division by zero error |
β Common Mistakes to Avoid
Mistake | Problem |
---|---|
5 / 2 = 2.5 (wrong) | Result is 2 if both are int |
5.0 % 2 (invalid) | Modulus only works on ints |
Division by zero | Runtime error |
Arithmetic Operator Precedence
When combining operators, precedence rules apply (like in math):
*
,/
,%
(evaluated left to right)+
,-
(evaluated left to right)
Use parentheses ()
to force evaluation order.
β Example:
int result = 10 + 5 * 2; // result = 20
int fixed = (10 + 5) * 2; // fixed = 30