How to Use the Not-Equal (!=) Operator in C++?
Last Updated :
08 Feb, 2024
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++
#include <iostream>
using namespace std;
int main()
{
int num1 = 10;
int num2 = 20;
if (num1 != num2) {
cout << num1 << " is not equal to " << num2 << endl;
}
else {
cout << num1 << " is equal to " << num2 << endl;
}
return 0;
}
|
Output
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++
#include <iostream>
using namespace std;
#include <iostream>
int main()
{
int arr[] = { 2, 4, 6, 8, 10 };
int target = 6;
bool found
= false ;
int i = 0;
int n = sizeof (arr)
/ sizeof (
arr[0]);
while (i != n) {
if (arr[i] == target) {
found = true ;
break ;
}
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;
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...