How to compare characters in the C language?
In the C language, characters can be compared using relational operators. For example, characters can be compared for their ordering using “<", ">“, “<=", ">=”, “==”, “!=”, and other operators.
These operators compare the ASCII code of characters. ASCII code represents characters in computers, and each character has a corresponding ASCII code. In ASCII code, characters are arranged in alphabetical order.
Below is an example code for comparing the size of characters.
#include <stdio.h>
int main() {
char c1 = 'a';
char c2 = 'b';
if (c1 < c2) {
printf("%c is smaller than %c\n", c1, c2);
} else if (c1 > c2) {
printf("%c is greater than %c\n", c1, c2);
} else {
printf("%c and %c are equal\n", c1, c2);
}
return 0;
}
In the code above, we compared the sizes of characters c1 and c2. Based on the order of ASCII codes, the ASCII code for the character ‘a’ is smaller than the ASCII code for the character ‘b’, so the output is: “a is smaller than b”.