Relational operators are essential components of C programming that allow you to compare values and make decisions based on the results. In this article, we’ll explore the basics of C programming’s relational operators, including ==
(equal to), !=
(not equal to), <
(less than), >
(greater than), <=
(less than or equal to), and >=
(greater than or equal to). Through real-world examples and output demonstrations, you’ll gain a firm grasp of how to use these operators effectively. Relational operators are indispensable tools in C programming, enabling you to make decisions based on comparisons between values. In this article, we’ve explored the basic relational operators (==, !=, <, >, <=, and >=) with real-world examples and output demonstrations. Armed with this knowledge, you’re well-equipped to write more complex C programs that involve decision-making and conditional statements.
Equal To (==)
The ==
operator is used to compare two values for equality. If the values are equal, it returns true
; otherwise, it returns false
. Let’s illustrate this with an example:
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 5;
if (num1 == num2) {
printf("num1 is equal to num2\n");
} else {
printf("num1 is not equal to num2\n");
}
return 0;
}
Output:
num1 is not equal to num2
Not Equal To (!=)
The !=
operator is used to check if two values are not equal. If they are not equal, it returns true
; otherwise, it returns false
. Here’s an example:
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 5;
if (num1 != num2) {
printf("num1 is not equal to num2\n");
} else {
printf("num1 is equal to num2\n");
}
return 0;
}
Output:
num1 is not equal to num2
Less Than (<) and Greater Than (>)
The <
and >
operators are used to compare values to check if one is less than or greater than the other. Let’s examine both operators with examples:
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 5;
if (num1 < num2) {
printf("num1 is less than num2\n");
} else {
printf("num1 is not less than num2\n");
}
if (num1 > num2) {
printf("num1 is greater than num2\n");
} else {
printf("num1 is not greater than num2\n");
}
return 0;
}
Output:
num1 is not less than num2
num1 is greater than num2
Less Than or Equal To (<=) and Greater Than or Equal To (>=)
The <=
and >=
operators are used to check if one value is less than or equal to or greater than or equal to another value, respectively. Let’s see how they work in practice:
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 10;
if (num1 <= num2) {
printf("num1 is less than or equal to num2\n");
} else {
printf("num1 is not less than or equal to num2\n");
}
if (num1 >= num2) {
printf("num1 is greater than or equal to num2\n");
} else {
printf("num1 is not greater than or equal to num2\n");
}
return 0;
}
Output:
num1 is less than or equal to num2
num1 is greater than or equal to num2