In C programming, operators are used to perform various operations on variables and values. There are three main types of operators in C programming: arithmetic, relational, and logical operators. Each type of operator has its own set of rules and syntax for use in code. In this article, we will discuss each type of operator in detail and provide examples of how to use them in your code.
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations on variables and values in C programming. These operators include addition (+), subtraction (-), multiplication (*), division (/), and module (%), which returns the remainder of a division operation.
For example:
copy
#include <stdio.h>
int main() {
int a = 20, b = 3;
int add, sub, mul, div, remainder;
add = a + b;
sub = a - b;
mul = a * b;
div = a / b;
remainder = a % b;
printf("add = %d, sub = %d, mul = %d, div = %d, remainder = %d", add, sub, mul, div, remainder);
return 0;
}
Output:
copy
add = 23, sub = 17, mul = 60, div = 6, remainder = 2
Relational Operators:
Relational operators are used to compare two values in C programming. They include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). The result of a relational operation is a boolean value (true or false). For example:
copy
#include <stdio.h>
int main() {
int a = 20, b = 3;
int equal, not_equal, greater;
equal = (a == b);
not_equal = a != b;
greater = a < b;
printf("equal = %d, not_equal = %d, greater = %d", equal, not_equal, greater);
return 0;
}
Output: equal = 0, not_equal = 1, greater = 0
Logical Operators:
Logical operators are used to combine two or more conditions in C programming. They include logical AND (&&), logical OR (||), and logical NOT (!). The result of a logical operation is also a boolean value (true or false). For example:
copy
#include <stdio.h>
int main() {
int and, or, not;
and = ((5 < 4) && (10 > 5)); // if all conditions are true, return 1, otherwise return 0
or = ((5 < 4) || (10 > 5)); // if at least one condition is true, return 1, otherwise return 0
not = !((5 < 4)); // if the condition is true, return 0, otherwise return 1
printf("and = %d, or = %d, not = %d", and, or, not);
return 0;
}
Output: and = 0, or = 1, not = 1