C Greater-Than Operator
In C, the Greater-Than >
operator is a comparison operator used to check if the left operand is greater than the right operand. If the left operand is greater, the operator returns true
(1); otherwise, it returns false
(0). The Greater-Than >
operator is commonly used in conditional statements like if
and loops.
Syntax of the Greater-Than Operator
The syntax to use the Greater-Than operator is:
variable1 > variable2
Explanation:
variable1
: The first operand in the comparison.>
: The greater-than comparison operator.variable2
: The second operand to compare againstvariable1
.
The result of the comparison is 1
(true) if variable1
is greater than variable2
, otherwise 0
(false).
Examples of the Greater-Than Operator
1. Comparing Two Integer Values
In this example, we will compare two integer values using the Greater-Than >
operator and print the result.
main.c
#include <stdio.h>
int main() {
int a = 15, b = 10;
if (a > b) {
printf("%d is greater than %d\n", a, b);
} else {
printf("%d is not greater than %d\n", a, b);
}
return 0;
}
Explanation:
- We declare two integer variables
a
andb
, initialized to 15 and 10. - The
if
condition checks ifa > b
. - Since
15 > 10
is true, the message “15 is greater than 10” is printed.
Output:
15 is greater than 10
2. Comparing Floating-Point Numbers
In this example, we will use the Greater-Than >
operator to compare two floating-point numbers.
main.c
#include <stdio.h>
int main() {
float x = 9.5, y = 12.3;
if (x > y) {
printf("%.1f is greater than %.1f\n", x, y);
} else {
printf("%.1f is not greater than %.1f\n", x, y);
}
return 0;
}
Explanation:
- We declare two float variables
x
andy
with values 9.5 and 12.3. - The condition
x > y
checks if 9.5 is greater than 12.3. - Since
9.5 > 12.3
is false, theelse
block prints “9.5 is not greater than 12.3.”
Output:
9.5 is not greater than 12.3
3. Using Greater-Than in a Loop
In this example, we will use the Greater-Than >
operator to control a loop that prints numbers greater than 5.
main.c
#include <stdio.h>
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Numbers greater than 5: ");
for (int i = 0; i < size; i++) {
if (numbers[i] > 5) {
printf("%d ", numbers[i]);
}
}
return 0;
}
Explanation:
- We declare an array
numbers[]
with five elements: {2, 4, 6, 8, 10}. - The
for
loop iterates through the array. - Inside the loop, the condition
numbers[i] > 5
checks if an element is greater than 5. - Only numbers greater than 5 are printed.
Output:
Numbers greater than 5: 6 8 10
Conclusion
In this tutorial, we covered the Greater-Than >
operator in C:
- The Greater-Than
>
operator checks if one value is greater than another. - It returns
1
(true) if the first value is greater, otherwise0
(false). - It is commonly used in conditional statements and loops.
The Greater-Than >
operator is an essential tool for making logical comparisons in C programming.