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
.
Operator | Description |
---|---|
< | 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 |
#include <iostream>
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;
}
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
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
.while
loop is used to execute a block of code repeatedly as long as a certain condition is true.(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
.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.(a != b && i >= a+b)
becomes false, the loop terminates, and the program continues with the next line of code.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.