Relational and logical operators

Relational operators are used to compare values with each other. They return a logical result: true or false. Values that are linked with relational operators are called elementary statements in propositional logic.
A typical example of a Boolean logical operator is the and operation: It always returns true if all operands are also true.

OperatorDescription
<smaller
<=less than or equal to
>greater
>=greater than or equal to
==equal
!=unequal
!expression is false
&&both expressions are true
||at least one expression is true

Code Example

#include &lt;iostream&gt;
using namespace std;

int main() {
	int a = 0, i = 20, b = 8;
	while (a != b && i >= a+b) {
		cout << a << " is equal " << b << endl;
		a++;
	}
	cout << a << " is unequal " << b << endl;
}
Output
0 is equal 8
1 is equal 8
2 is equal 8
3 is equal 8
4 is equal 8
5 is equal 8
6 is equal 8
7 is equal 8
8 is unequal 8

Code Explanation

  1. The code includes the iostream library, which provides input and output functionality in C++.
  2. The line using namespace std; declares that we’re using the std namespace, which contains various standard C++ functions and objects, including cout.
  3. The int main() function is the entry point of the program. It returns an integer value, typically 0, indicating successful execution.
  4. Inside the main() function, three variables are declared and initialized:
    • a is an int variable initialized with the value 0.
    • i is an int variable initialized with the value 20.
    • b is an int variable initialized with the value 8.
  5. The while loop is used to execute a block of code repeatedly as long as a certain condition is true.
  6. The condition (a != b && i >= a+b) is checked before each iteration of the loop. The loop will continue as long as a is not equal to b and the value of i is greater than or equal to the sum of a and b.
  7. If the condition is true, the code block inside the loop is executed. The code outputs the string a is equal b, where a and b are the values of the variables, and then increments the value of a by 1 using the a++ statement.
  8. Once the condition (a != b && i >= a+b) becomes false, the loop terminates, and the program continues with the next line of code.
  9. The line cout << a << " is unequal " << b << endl; outputs the string a is unequal b, where a and b are the final values of the variables after the loop.