C Less-Than Operator
In C, the Less-Than <
operator is a comparison operator used to check whether the left operand is smaller than the right operand. If the left operand is smaller, the operator returns true
(1); otherwise, it returns false
(0).
The Less-Than <
operator is commonly used in conditional statements and loop conditions.
Syntax of the Less-Than Operator
The syntax to use the Less-Than operator is:
variable1 < variable2
Explanation:
variable1
: The first operand to compare.<
: The less-than comparison operator.variable2
: The second operand to compare with the first operand.
The result of the comparison is 1
(true) if variable1
is smaller than variable2
, otherwise 0
(false).
Examples of the Less-Than Operator
1. Comparing Two Integer Values
In this example, we will compare two integer values using the Less-Than <
operator and print the result.
main.c
#include <stdio.h>
int main() {
int a = 10, b = 20;
if (a < b) {
printf("%d is less than %d\n", a, b);
} else {
printf("%d is not less than %d\n", a, b);
}
return 0;
}
Explanation:
- We declare two integer variables
a
andb
, initialized to 10 and 20. - The
if
condition checks ifa < b
. - Since
10 < 20
is true, the message “10 is less than 20
” is printed.
Output:
10 is less than 20
2. Using Less-Than Operator in a Loop
In this example, we will use the Less-Than <
operator in a while loop condition to print numbers from 1 to 5.
main.c
#include <stdio.h>
int main() {
int i = 1;
while (i < 6) {
printf("%d ", i);
i++;
}
return 0;
}
Explanation:
- We initialize
i
to 1. - The
while
loop runs as long asi < 6
. - Inside the loop,
i
is printed and incremented by 1. - The loop terminates when
i
reaches 6.
Output:
1 2 3 4 5
3. Using Less-Than Operator with Floating-Point Numbers
In this example, we will compare two floating-point numbers using the Less-Than <
operator.
main.c
#include <stdio.h>
int main() {
float x = 5.5, y = 7.2;
if (x < y) {
printf("%.1f is less than %.1f\n", x, y);
} else {
printf("%.1f is not less than %.1f\n", x, y);
}
return 0;
}
Explanation:
- We declare two floating-point variables
x
andy
with values 5.5 and 7.2. - The
if
condition checks ifx < y
. - Since
5.5 < 7.2
is true, the message “5.5 is less than 7.2
” is printed.
Output:
5.5 is less than 7.2
Conclusion
In this tutorial, we covered the Less-Than <
operator in C:
- The Less-Than
<
operator is used to check if one value is smaller than another. - It returns
1
(true) if the first operand is smaller and0
(false) otherwise. - It is commonly used in conditional statements and loops.