C Programming
In this tutorial we will learn about arithmetic operators in C programming language.
C programming language provides us with all the basic arithmetic operators.
Operator | Description |
---|---|
+ | Addition or unary plus |
- | Subtraction or unary minus |
* | Multiplication |
/ | Division |
% | Modulo division |
In the following example we will add two numbers using the addition operator.
#include <stdio.h>
int main(void)
{
int
a = 10,
b = 20;
int sum = a + b;
printf("Sum: %d\n", sum);
return 0;
}
Output
Sum: 30
In the following example we will subtract two numbers using the subtraction operator.
#include <stdio.h>
int main(void)
{
int
a = 10,
b = 20;
int diff = a - b;
printf("Difference: %d\n", diff);
return 0;
}
Output
Difference: -10
In the following example we will multiply two numbers using the multiplication operator.
#include <stdio.h>
int main(void)
{
int
a = 10,
b = 20;
int prod = a * b;
printf("Product: %d\n", prod);
return 0;
}
Output
Product: 200
In the following example we will divide two numbers using the division operator.
#include <stdio.h>
int main(void)
{
int
a = 100,
b = 10;
int quot = a / b;
printf("Quotient: %d\n", quot);
return 0;
}
Output
Quotient: 10
During integer division, if both the operators are of the same sign, the result is truncated towards zero. If one of them is negative, the direction of truncation is implementation dependent.
Example:
6 / 7 = 0 and -6 / -7 = 0
But -6 / 7 may be 0 or -1 (machine dependent)
When one of the operand is real and the other is integer, the expression is called mixed-mode arithmetic. If either of the operand is of the real type, then only the real operation is performed. If both operand is integer then fractional part is truncated.
Example:
5 / 10.0 = 0.5
Whereas, 15 / 10 = 1 (fractional part 0.5 is truncated)
Modulo operator gives us the remainder.
In the following example we will divide two numbers and get the remainder using the modulo operator.
#include <stdio.h>
int main(void)
{
int
a = 9,
b = 4;
int rem = a % b;
printf("Remainder: %d\n", rem);
return 0;
}
Output
Remainder: 1
Modulo operator %
can't be used on floating point value.
ADVERTISEMENT