How to Use Arithmetic Operators in C: Syntax and Examples
In C, you use
arithmetic operators like +, -, *, /, and % to perform basic math operations on numbers. These operators work with variables and constants to add, subtract, multiply, divide, or find the remainder of integer division.Syntax
Arithmetic operators in C are used between two operands (numbers or variables) to perform calculations. The main operators are:
+for addition-for subtraction*for multiplication/for division%for modulus (remainder of division)
Example syntax: result = a + b; means add a and b and store the result.
c
result = a + b; result = a - b; result = a * b; result = a / b; result = a % b;
Example
This example shows how to use all basic arithmetic operators with integer variables and print the results.
c
#include <stdio.h> int main() { int a = 10, b = 3; printf("a = %d, b = %d\n", a, b); printf("Addition: a + b = %d\n", a + b); printf("Subtraction: a - b = %d\n", a - b); printf("Multiplication: a * b = %d\n", a * b); printf("Division: a / b = %d\n", a / b); printf("Modulus: a %% b = %d\n", a % b); return 0; }
Output
a = 10, b = 3
Addition: a + b = 13
Subtraction: a - b = 7
Multiplication: a * b = 30
Division: a / b = 3
Modulus: a % b = 1
Common Pitfalls
Common mistakes when using arithmetic operators in C include:
- Using
/with integers results in integer division, which drops the decimal part. - Dividing by zero causes a runtime error.
- Using
%with non-integers is not allowed. - For floating-point division, at least one operand must be a float or double.
Example of integer division vs floating-point division:
c
#include <stdio.h> int main() { int a = 7, b = 2; printf("Integer division: 7 / 2 = %d\n", a / b); // result is 3 double x = 7.0, y = 2.0; printf("Floating-point division: 7.0 / 2.0 = %.2f\n", x / y); // result is 3.50 // Wrong: double z = a % b; // error: modulus with float return 0; }
Output
Integer division: 7 / 2 = 3
Floating-point division: 7.0 / 2.0 = 3.50
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division (integer if both operands int) | 5 / 3 | 1 |
| % | Modulus (remainder of integer division) | 5 % 3 | 2 |
Key Takeaways
Use +, -, *, /, and % to perform basic math operations in C.
Integer division drops decimals; use float or double for precise division.
Modulus % works only with integers and gives the remainder.
Avoid dividing by zero to prevent runtime errors.
Always match operand types to get expected results.