Check If Two Variable Is Not Equal In C++
Code snippet for how to Check If Two Variable Is Not Equal In C++ with sample and detail explanation
In writing codes or creating programs, there are numerous occasions where you may need to compare the values of two variables. In this article, we will dive into the process of checking if two variables are not equal in C++.
Code snippet: Checking if two variables are not equal
The code below demonstrates a simple method of comparing two integers in C++.
#include <iostream>
int main() {
int var1 = 5;
int var2 = 10;
if(var1 != var2) {
std::cout << "The variables are not equal.";
} else {
std::cout << "The variables are equal.";
}
return 0;
}
Code Explanation for Checking if two variables are not equal
In the given code snippet, we are mainly looking at how the ‘!=’ operator functions. This operator performs the logic of ‘Not Equals’ in C++, and it provides us with a relatively easy and accurate way of comparing two variable values.
The steps involved in this code snippet are:
-
Step One:
Start by including the “iostream” header file. This file is included to allow the code to output a string through the standard output (std::cout).
#include <iostream>
-
Step Two:
Then, we define two integer variables – ‘var1’ and ‘var2’ – and assign them values 5 and 10, respectively.
int var1 = 5;
int var2 = 10;
-
Step Three:
Next, we use an ‘if’ statement to compare the two variables using the ‘not equal to’ operator (’!=’). This operator will return ‘true’ if var1 is not equal to var2 or ‘false’ if they are equal.
if(var1 != var2)
-
Step Four:
If the condition is true (that is, var1 is not equal to var2), we instruct the program to print “The variables are not equal.”
{
std::cout << "The variables are not equal.";
}
-
Step Five:
If the condition is false (meaning var1 is equal to var2), the program prints “The variables are equal.”
else {
std::cout << "The variables are equal.";
}
-
Step Six:
The ‘return 0;’ at the end of the code is used to indicate that the program has executed successfully without any error.
return 0;
By following these steps, you can seamlessly check if two variable values are not equal in C++, which is a common requirement in many coding scenarios.