The not-equal operator is a fundamental comparison operator in C++ represented by “!=”. It is used for making decisions in programming and is hence called a conditional operator. In this article, we will discuss how to use the Not-Equal (!=) operator in C++.
Not-Equal (!=) Operator in C++
The not-equal operator(!=) evaluates two values and returns a boolean value.
- It returns true when both values are not equal.
- It returns false if they are equal
The not equal to the operator is a binary operator so it is used with the two operands:
operand1 != operand2
It only allows for branching when both values are different and can be used to make decisions based on a given condition.
How to Use the Not-Equal (!=) Operator in C++?
The following examples show how can we use the not-equal operator in our C++ programs:
Example 1
The below example demonstrates the use of the not-equal operator in conditional statements.
// C++ program to demonstrate the use of the not-equal // operator in conditional statements. #include <iostream> using namespace std;
int main()
{ // creating two integer numbers
int num1 = 10;
int num2 = 20;
// Check if the two numbers are not equal
if (num1 != num2) {
cout << num1 << " is not equal to " << num2 << endl;
}
else {
cout << num1 << " is equal to " << num2 << endl;
}
return 0;
} |
10 is not equal to 20
Explanation: In above example, we are using Not-Equal Operator (!=) that checks whether the num1 and num2 are equal or not. As 10 and 20 are not equal so the block of code inside if statement is executed and prints ” 10 is not equal to 20 “.
Example 2
The below example demonstrates the use of not-equal operator in loops.
// C++ program to demonstrate the use of not-equal operator // in loops. #include <iostream> using namespace std;
#include <iostream> int main()
{ int arr[] = { 2, 4, 6, 8, 10 }; // Sample array
int target = 6; // Number to find
bool found
= false ; // Flag to indicate if the number is found
int i = 0;
int n = sizeof (arr)
/ sizeof (
arr[0]); // Calculate the size of the array
// Loop through the array using the not-equal operator
while (i != n) {
if (arr[i] == target) {
found = true ;
break ; // Exit the loop if the number is found
}
i++;
}
if (found) {
cout << "Number " << target
<< " is present in the array." << endl;
}
else {
cout << "Number " << target << " is not present in the array." << endl;
}
return 0;
} |
The number 6 is not present in the array.
Explanation: In above example, we are checking that a target is present in array or not by using a not equal operator to loop in array until iterator i is not equal to size of array.