In C programming, arithmatic operators are used to perform mathematical operations. For example: addition, subtraction, multiplication, division, and modulus.
C supports five arithmetic operators.
Operator | Description |
---|
+ | Unary plus or binary addition |
- | Unary minus or binary subtraction |
* | Multiplication |
/ | Division |
% | Modulo division (Evaluates remainder)
|
Unary plus (+) and unary minus (-) operator:
Unary operators required only one operand and used to indicates the number is positive or negative.
For Example:
- a = -10; // a holds -10 (negative)
- b = +3.14; // b holds +3.14 (positive)
- c = -b; // c holds -(+3.14) => -3.14 (negative)
- d = -a; // d holds -(-10) => +10 (positive)
By default, every number is positive. Therefore, use of unary plus operator is optional. Means b = +3.14; is equivalent to b = 3.14;.
Binary arithmatic operators:
Binary arithmatic operators work with two operands. which are used to perform basic arithmatic operation like addition, subtraction, multiplication, division, and modulus (%).
Suppose two integer variables x and y with initial values.
int x=20, y=10;
After performing following binary arithmetic operations.
- x + y = 30;
- x - y = 10;
- x * y = 200;
- x / y = 2; // quotient = 2, of integer division
- x % y = 0; // Remainder = 0, of integer division
Integer division:
C performs integer division if both operands are integer type. Integer division always evaluates to an integer discarding the fractional part.
For Example:
Operation | Result | Division type |
---|
5 / 2 | 2 | Integer division |
Real division:
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.
For Example:
Operation | Result | Division type |
---|
10 / 2.0 | 5.0 | Real division |
5.0 / 2 | 2.5 | Real division |
5 / 2.0 | 2.5 | Real division |
5.0 / 2.0 | 2.5 | Real division |
Mudulo division %:
Modulo division evaluates remainder after performing division of two numbers.
1) Modulo division is only possible with integer operands. It causes compilation error with float types. 2) Modulo operator returns sign of the first operand.
For Example:
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 |
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.