C Not-Equal Operator
In C, the Not-Equal != operator is a comparison operator used to check whether two values are different. If the values are not equal, the operator returns true (1); otherwise, it returns false (0).
The Not-Equal != operator is commonly used in conditional statements like if and loop conditions.
Syntax of the Not-Equal Operator
The syntax to use the Not-Equal operator is:
variable1 != variable2
Explanation:
variable1: The first operand to compare.!=: The not-equal comparison operator.variable2: The second operand to compare with the first operand.
The result of the comparison is 1 (true) if the operands are not equal, otherwise 0 (false).
Examples of the Not-Equal Operator
1. Using Not-Equal to Compare Two Integers
In this example, we will compare two integer values using the Not-Equal != operator and print the result.
main.c
#include <stdio.h>
int main() {
int a = 10, b = 20;
if (a != b) {
printf("Numbers are not equal.\n");
} else {
printf("Numbers are equal.\n");
}
return 0;
}
Explanation:
- We declare two integer variables
aandb, initialized to 10 and 20. - The
ifcondition checks ifa != b. - Since
10 != 20is true, the message “Numbers are not equal.” is printed.
Output:
Numbers are not equal.
2. Using Not-Equal with Different Data Types
In this example, we will compare a character and an integer using the Not-Equal != operator.
main.c
#include <stdio.h>
int main() {
char ch = 'A';
int num = 65;
if (ch != num) {
printf("Character and number are not equal.\n");
} else {
printf("Character and number are equal.\n");
}
return 0;
}
Explanation:
- We declare a character variable
chwith value ‘A’ and an integernumwith value 65. - The ASCII value of ‘A’ is 65, so
ch != numevaluates to false. - Since the condition is false, “Character and number are equal.” is printed.
Output:
Character and number are equal.
3. Using Not-Equal to Control a Loop
In this example, we will use the Not-Equal != operator to terminate a while loop when a specific condition is met.
main.c
#include <stdio.h>
int main() {
int i = 1;
// Loop runs until i is not equal to 5
while (i != 5) {
printf("i = %d\n", i);
i++;
}
return 0;
}
Explanation:
- We initialize
ito 1. - The
whileloop runs as long asi != 5. - Inside the loop,
iis printed and incremented by 1. - The loop terminates when
ibecomes 5.
Output:
i = 1
i = 2
i = 3
i = 4
Conclusion
In this tutorial, we covered the Not-Equal != operator in C:
- The Not-Equal
!=operator checks if two values are different. - It returns
1(true) if the values are not equal and0(false) if they are equal. - It is used in conditional statements and loops to control program flow.
The Not-Equal != operator is essential for decision-making and loop control in C programming.
