Arithmetic operators in C are symbols used to perform arithmetic operations on operands, which can be constants, variables, or expressions. These operators enable basic arithmetic calculations such as addition, subtraction, multiplication, division, and modulus. Let’s explore each arithmetic operator in detail:
Addition Operator (+):
- The addition operator (+) is used to add two operands.
- Syntax: operand1 + operand2
- Example: int sum = 5 + 3; (sum will be 8)
Subtraction Operator (-):
- The subtraction operator (–) is used to subtract the second operand from the first operand.
- Syntax: operand1 – operand2
- Example: int difference = 10 – 3; (difference will be 7)
Multiplication Operator (*):
- The multiplication operator (*) is used to multiply two operands.
- Syntax: operand1 * operand2
- Example: int product = 4 * 5; (product will be 20)
Division Operator (/):
- The division operator (/) is used to divide the first operand by the second operand.
- Syntax: operand1 / operand2
- Example: int quotient = 20 / 4; (quotient will be 5)
Modulus Operator (%):
- The modulus operator (%) returns the remainder of the division of the first operand by the second operand.
- Syntax: operand1 % operand2
- Example: int remainder = 10 % 3; (remainder will be 1)
Operator Precedence:
- Arithmetic operators follow the rules of operator precedence, where multiplication, division, and modulus have higher precedence than addition and subtraction.
- Parentheses can be used to specify the order of operations, overriding the default precedence.
- Example: int result = (5 + 3) * 2; (result will be 16)
Mixed-Type Arithmetic:
- In C, arithmetic operations involving operands of different data types result in implicit type conversion.
- The operands are promoted to a common type before the operation is performed.
- For example, if one operand is an int and the other is a float, the int operand will be promoted to float before performing the operation.
Integer Division:
- In C, division of two integers truncates any fractional part, resulting in an integer quotient.
- To perform floating-point division, at least one of the operands must be a floating-point type.
Conclusion:
Arithmetic operators in C provide the means to perform basic mathematical calculations in programs. Understanding how to use these operators and their precedence rules is essential for writing correct and efficient C code. By mastering arithmetic operators, programmers can perform a wide range of calculations, from simple addition to more complex mathematical operations.