
Arithmetic Operators in C
Arithmetic operators are used to perform mathematical calculations in C programming.
"Arithmetic operators are the foundation of numerical computations in C programming."
What Are Arithmetic Operators?
Arithmetic operators are symbols that perform mathematical operations like addition, subtraction, multiplication, division, and modulus on numeric values.
List of Arithmetic Operators
Operator | Description | Example | Result (if a = 10, b = 3) |
---|---|---|---|
+ |
Addition | a + b |
10 + 3 = 13 |
- |
Subtraction | a - b |
10 - 3 = 7 |
* |
Multiplication | a * b |
10 * 3 = 30 |
/ |
Division | a / b |
10 / 3 = 3 (integer division) |
% |
Modulus (Remainder) | a % b |
10 % 3 = 1 |
Examples of Arithmetic Operators
1. Basic Arithmetic Operations
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division (Integer): %d\n", a / b);
printf("Modulus: %d\n", a % b);
return 0;
}
2. Performing Arithmetic Operations with User Input
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
printf("Difference = %d\n", a - b);
printf("Product = %d\n", a * b);
printf("Quotient = %d\n", a / b);
printf("Remainder = %d\n", a % b);
return 0;
}
3. Floating-Point Arithmetic
#include <stdio.h>
int main() {
float a = 5.5, b = 2.2;
printf("Addition: %.2f\n", a + b);
printf("Subtraction: %.2f\n", a - b);
printf("Multiplication: %.2f\n", a * b);
printf("Division: %.2f\n", a / b);
return 0;
}
Important Notes on Arithmetic Operators
- Integer Division: When dividing integers, the decimal part is discarded.
- Floating-Point Precision: Use
float
ordouble
for more precise calculations. - Modulus Operator (%): Works only with integers.
Best Practices for Using Arithmetic Operators
- Use
float
ordouble
for division to avoid truncation. - Be mindful of division by zero errors.
- Use parentheses for clarity in complex expressions.
Example: Handling Division by Zero
#include <stdio.h>
int main() {
int a = 10, b = 0;
if (b != 0) {
printf("Division result: %d\n", a / b);
} else {
printf("Error: Division by zero is not allowed.\n");
}
return 0;
}
Conclusion
Arithmetic operators in C are essential for performing mathematical operations. Mastering them will help you build efficient and accurate programs! 🚀