C++ Lec6-Operaters2
C++ Lec6-Operaters2
Comparison Operators
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x == y); // returns 0 (false) because 5 is not equal to 3
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x != y); // returns 1 (true) because 5 is not equal to 3
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x < y); // returns 0 (false) because 5 is not less than 3
return 0;}
Programming C++ Samir Bilal Practical & Theoretical
3
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x >= y); // returns 1 (true) because five is greater than, or equal, to 3
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x <= y); // returns 0 (false) because 5 is neither less than or equal to 3
return 0;
}
Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
&& ||
!
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > 3 && x < 10); // returns true (1) because 5 is greater than 3 AND 5 is less than 10
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > 3 || x < 4); // returns true (1) because one of the conditions are true (5 is greater
than 3, but 5 is not less than 4)
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (!(x > 3 && x < 10)); // returns false (0) because ! (not) is used to reverse the result
return 0; }
Programming C++ Samir Bilal Practical & Theoretical
6
Q1) How many comparison operators we have list six of them and write the name with
example?
Q2) Define logical operators & how many logical operators we have list them with( name,
description and example)
Q3) What are the truth table of (and, or , not)?