The objective of the Level 5 Diploma in Information Technology is to provide learners with an excellent foundation for a career in a range of organisations. It designed to ensure that each learner is ‘business ready’: a confident, independent thinker with a detailed knowledge of Information Technology, and equipped with the skills to adapt rapidly to change.
2. Logical Operators
Use logical operators to combine conditional statements and return true or false.
The AND operator works the following way:
In the AND operator,
both operands must
be true for the entire
expression to be true.
3. The AND Operator
For example:
int age = 20;
if (age > 16 && age < 60) {
cout << "Accepted!" << endl;
}
In the example above, the logical AND operator was used to combine both expressions.
The expression in the if statement evaluates to true only if both expressions are true.
4. The AND Operator
Within a single if statement, logical operators can be used to combine multiple conditions.
int age = 20;
int grade = 80;
if (age > 16 && age < 60 && grade > 50) {
cout << "Accepted!" << endl;
}
5. The OR Operator
The OR (||) operator returns true if any one of its operands is true.
Example:
int age = 16;
int score = 90;
if (age > 20 || score
> 50) {
cout << "Accepted!"
<< endl;
}
You can combine any number of logical OR statements you want.
In addition, multiple OR and AND statements may be chained together.
6. Logical NOT
The logical NOT (!) operator works with just a single operand, reversing its logical state. Thus, if a
condition is true, the NOT operator makes it false, and vice versa.
int age = 10;
if ( !(age > 16) ) {
cout << "Your age is less than 16" << endl;
}
// Outputs "Your age is less than 16"
Be careful
using this,
because !false
means true.
7. while vs. do...while
Try the following example to understand all the logical operators
#include <iostream>
using namespace std;
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
cout << "Line 1 - Condition is
true"<< endl ;
}
if(a || b) {
cout << "Line 2 - Condition is
true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if(a && b) {
cout << "Line 3 - Condition is
true"<< endl ;
} else {
cout << "Line 4 - Condition is
not true"<< endl ;
}
if(!(a && b)) {
cout << "Line 5 - Condition is
true"<< endl ;
}
return 0;