C Less-Than Or Equal-To Operator
In C, the Less-Than Or Equal-To <= operator is a comparison operator used to check whether the left-hand operand is less than or equal to the right-hand operand. If the condition is met, the operator returns 1 (true); otherwise, it returns 0 (false). This operator is commonly used in conditional statements like if and in loops to control iteration.
Syntax of the Less-Than Or Equal-To Operator
The syntax to use the Less-Than Or Equal-To operator is:
variable1 <= variable2
Explanation:
variable1: The first operand to compare.<=: The Less-Than Or Equal-To comparison operator.variable2: The second operand to compare with the first operand.
The result of the comparison is 1 (true) if variable1 is less than or equal to variable2, otherwise 0 (false).
Examples of the Less-Than Or Equal-To Operator
1. Using Less-Than Or Equal-To to Compare Two Integers
In this example, we will compare two integer values using the Less-Than Or Equal-To <= operator and print the result.
main.c
#include <stdio.h>
int main() {
int a = 10, b = 15;
if (a <= b) {
printf("a is less than or equal to b.\n");
} else {
printf("a is greater than b.\n");
}
return 0;
}
Explanation:
- We declare two integer variables
aandb, initialized to 10 and 15. - The
ifcondition checks ifa <= b. - Since
10 <= 15is true, the message “a is less than or equal to b.” is printed.
Output:
a is less than or equal to b.
2. Using Less-Than Or Equal-To in a Loop Condition
In this example, we will use the Less-Than Or Equal-To <= operator to control the number of iterations in a for loop.
main.c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
Explanation:
- We use a
forloop where the loop variableistarts from 1. - The loop condition
i <= 5ensures that the loop runs as long asiis less than or equal to 5. - On each iteration,
iis printed and incremented by 1. - The loop terminates when
ibecomes greater than 5.
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
3. Using Less-Than Or Equal-To with Floating-Point Numbers
In this example, we will compare two floating-point numbers using the Less-Than Or Equal-To <= operator.
main.c
#include <stdio.h>
int main() {
float num1 = 5.5, num2 = 5.5;
if (num1 <= num2) {
printf("num1 is less than or equal to num2.\n");
} else {
printf("num1 is greater than num2.\n");
}
return 0;
}
Explanation:
- We declare two floating-point variables
num1andnum2both initialized to 5.5. - The
ifcondition checks ifnum1 <= num2. - Since
5.5 <= 5.5is true, “num1 is less than or equal to num2.” is printed.
Output:
num1 is less than or equal to num2.
Conclusion
In this tutorial, we covered the Less-Than Or Equal-To <= operator in C:
- The
<=operator checks if one value is less than or equal to another. - It returns
1(true) if the condition is met, otherwise0(false). - It is commonly used in conditional statements and loop conditions.
