Arithmetic Operators: These operators are used to perform calculations such as addition, subtraction, multiplication, division, and modulus.
result = a + b;
result = a - b;
result = a * b;
result = a / b;
result = a % b;
#include <stdio.h>
int main() {
int num1 = 20, num2 = 5;
float decimalNum = 10.5f;
// Arithmetic operations examples
printf("Addition: %d + %d = %d\n", num1, num2, num1 + num2);
printf("Subtraction: %d - %d = %d\n", num1, num2, num1 - num2);
printf("Multiplication: %d * %d = %d\n", num1, num2, num1 * num2);
printf("Division: %d / %d = %.2f\n", num1, num2, (float)num1 / num2);
printf("Modulus: %d %% %d = %d\n", num1, num2, num1 % num2);
// Floating-point arithmetic operations example
float result = decimalNum + 5.7f;
printf("Addition of floats: %.2f + 5.7 = %.2f\n", decimalNum, result);
return 0;
}
What causes it: Misspelling an arithmetic operator or variable name.
# Bad code example that triggers the NameError
int res = a + b; // Misspelled '+' as 'res' instead of '+='
Error message:
Traceback (most recent call last):
File "example.py", line X, in <module>
error_code_here
NameError: name '+' is not defined
Solution: Correctly spell the arithmetic operator and variable names.
# Corrected code
int result = a + b; // Use proper spelling of '+' and 'result'
Why it happens: Spelling errors in code can cause unexpected behavior, resulting in NameErrors.
How to prevent it: Double-check your spelling and use an IDE with built-in spell checkers to help catch these mistakes.
What causes it: Attempting arithmetic operations on incompatible data types (e.g., int + float).
# Bad code example that triggers the TypeError
int num1 = 5;
float num2 = 3.5f;
int sum = num1 + num2; // Incorrect addition of incompatible data types
Error message:
Traceback (most recent call last):
File "example.py", line X, in <module>
error_code_here
TypeError: can't convert 'float' to 'int' without a parenthetic cast
Solution: Cast the data type to be compatible with arithmetic operations.
# Corrected code
int num1 = 5;
float num2 = 3.5f;
int sum = (int)(num1 + num2); // Parenthetically cast float to int before addition
Why it happens: Incompatible data types can't be directly combined without a typecast.
How to prevent it: Be aware of the data types you are working with and use proper type casting when needed.
Next steps for learning: Learn about comparison operators, logical operators, and bitwise operators in C language.