Arithmetic operators are used to perform basic arithmetic operations. Operations like addition, subtraction, multiplication, division and modulo division.
C supports five arithmetic operators.
Operator | Description |
---|---|
+ | Unary plus or binary addition |
- | Unary minus or binary subtraction |
* | Multiplication |
/ | Division |
% | Modulo division (Evaluates remainder) |
Important Note: There is no exponential operator in C programming language. Many beginners considers ^
(hat symbol) as an exponential operator. However, ^
is a bitwise XOR operator.
Unary plus and unary minus
The +
and -
arithmetic operators exhibits in two variants unary plus/minus and binary addition/subtraction. Unary plus and minus takes single operand and used to alter the sign of a real or integer type.
For example:
a = -5; // a contains -5
b = +10.65; // b contains +10.65
c = -a; // c contains -(-5) => +5
d = -b; // d contains –(+10.65) => -10.65
By default, every real or integer type is positive. Therefore, use of unary plus operator is optional. Means b = +10.65; is equivalent to b = 10.65;.
Binary arithmetic operators
Binary arithmetic operator are used to perform basic arithmetic operations. It accepts two operand.
Suppose two integer variables x and y with initial values
int x=10, y=6;
After performing following binary arithmetic operations.
x + y = 16
x - y = 4
x * y = 60
x / y = 1 (Integer division evaluates to integer trimming fractional part)
x % y = 4 (Remainder of the integer division)
Integer division
In computer programming divisions are performed differently. Apparently there are two types of division.
- Integer division
- Real division
C performs integer division if both operands are integer type. Integer division always evaluates to an integer discarding the fractional part.
C performs real division if any of the two operands are real type (either float
or double
). Real division evaluates to a real value containing integer as well as fractional part.
Consider the below division table for a clear view of division in C.
Operation | Result | Division type |
---|---|---|
5 / 2 | 2 | Integer division |
5.0 / 2 | 2.5 | Real division |
5 / 2.0 | 2.5 | Real division |
5.0 / 2.0 | 2.5 | Real division |
Modulo division
Modulo division evaluates remainder after performing division of two numbers. In C programming, we perform modulo division using %
operator. Many texts refers modulo operator as modulus operator.
Consider the below modulo division table for a clear view of modulo division operations in C.
Operation | Result |
---|---|
8 % 2 | 0 |
5 % 3 | 2 |
3 % 7 | 3 |
-3 % 7 | -3 |
5 % -2 | 1 |
-8 % -3 | -2 |
2.5 % 2 | Error |
8 % 2.5 | Error |
5.0 % 2.5 | Error |
Important note:
- Modulo division is only possible with integer operands. It causes compilation error with float types.
- Modulo operator returns sign of the first operand.