UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 4 · STUDENT NOTES
Comparison & Logical Operators
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
2 | Lecture4_Comparison_Logical_Operators.pptx | Practical 3 | N04 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 4.1 | Compare values with relational operators and explain that the result is a bool | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 4.2 | Combine conditions with &&, || and ! using truth tables | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 4.3 | Translate real-world rules (eligibility, leap year) into logical expressions | CLO1: Identify the necessary properties of good problem-solving techniques. | C3 |
SLO 4.4 | Find and fix common mistakes: = vs ==, chained comparisons, comparing doubles | CLO4: Describe the syntax and semantics of the C++ programming language. | C4 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. Where We Are
So far our programs only calculated. From today they will ask questions: Has the student passed? Is this a leap year? Can this person vote? The answer to every such question is true or false. These true/false answers are the base of every if statement (Lecture 7) and every loop (Lecture 9). (Slides L04-S02, S05)
2. Relational (Comparison) Operators
2.1 The six operators
Relational means "about the relation between two values". A relational operator compares two values and gives a bool answer. (Slide L04-S06)
Operator | Meaning | Example (a = 7, b = 10) | Result |
|---|---|---|---|
== | is equal to | a == b | false |
!= | is not equal to | a != b | true |
< | is less than | a < b | true |
> | is greater than | a > b | false |
<= | is less than or equal to | a <= 7 | true |
>= | is greater than or equal to | b >= 11 | false |
= is not == = assigns (puts a value into a box). == compares (asks "are these equal?"). Write two-character operators without a space: <=, >=, ==, !=. |
2.2 The result is a bool
C++ stores true as 1 and false as 0. By default cout prints 1 or 0. The manipulator boolalpha makes cout print the words true and false; it stays on for the rest of the program. (Slide L04-S07)
rel.cpp #include <iostream> using namespace std;
int main() { int a = 7, b = 10; cout << (a < b) << endl; // 1 cout << (a == b) << endl; // 0
cout << boolalpha; cout << (a != b) << endl; // true cout << (a >= 7) << endl; // true return 0; } |
Output 1 0 true true |
Keep brackets around a comparison inside cout. cout << a < b; is an error because << runs before <. Write cout << (a < b);.
2.3 Storing a condition in a bool variable
Give each condition a meaningful name that starts with is, has or can. The code then reads like English. (Slide L04-S08)
bool isPassed = marks >= 50; bool isFullMarks = marks == 100; bool canVote = age >= 18 && hasCnic; |
Real-world example A NADRA officer checks one rule and ticks a box on a form. A bool variable is that tick box: ticked (true) or empty (false). |
2.4 Comparing characters and strings
Characters are compared by their ASCII codes (Lecture 3, §4.4). Strings are compared letter by letter, like words in a dictionary. (Slide L04-S09)
Expression | Result | Why |
|---|---|---|
'a' < 'b' | true | 97 < 98 |
'Z' < 'a' | true | 90 < 97 — all capitals come before small letters |
'7' == 7 | false | the character '7' has code 55 |
"apple" < "banana" | true | a comes before b |
"ali" == "Ali" | false | small a (97) ≠ capital A (65) |
3. Logical Operators
3.1 AND, OR and NOT
Logical operators join small yes/no questions into one bigger question. They work on bool values and give a bool. (Slide L04-S10)
Operator | Name | Rule | Real-world example |
|---|---|---|---|
&& | AND | true only if BOTH sides are true | Admission: age is OK && marks are OK |
|| | OR | true if AT LEAST ONE side is true | Discount: student || senior citizen |
! | NOT | flips true ↔ false | !isRaining → go for a walk |
3.2 Truth tables
A truth table lists every possible input and the result. (Slide L04-S11)
A | B | A && B | A || B | !A |
|---|---|---|---|---|
false | false | false | false | true |
false | true | false | true | true |
true | false | false | true | false |
true | true | true | true | false |
Easy way to remember AND: one false makes it false. OR: one true makes it true. NOT: opposite. |
3.3 Worked example: who can vote?
Rule: a person can vote in Pakistan if they are 18 or older AND have a CNIC. (Slide L04-S12)
eligible.cpp #include <iostream> using namespace std;
int main() { int age; bool hasCnic; cout << "Enter age: "; cin >> age; cout << "Has CNIC? (1/0): "; cin >> hasCnic;
bool canVote = age >= 18 && hasCnic; cout << boolalpha << "Can vote: " << canVote << endl; return 0; } |
age | hasCnic | age >= 18 | canVote |
|---|---|---|---|
19 | 1 | true | true |
17 | 1 | false | false |
25 | 0 | true | false |
Testing tip: choose inputs that make each part of the condition true and false at least once.
3.4 Checking a range
In maths we write 20 ≤ temp ≤ 30. In C++ we must split it into two comparisons. (Slide L04-S13)
Question | C++ expression |
|---|---|
Inside the range 20–30 (pleasant weather) | temp >= 20 && temp <= 30 |
Outside the range (too cold or too hot) | temp < 20 || temp > 30 |
Is ch a capital letter? | ch >= 'A' && ch <= 'Z' |
4. Turning Real-World Rules into Expressions
4.1 Method
1. Read the rule and underline each small yes/no part.
2. Write each part as one comparison.
3. Join the parts with && (all must hold) or || (any one is enough). Use brackets to show the grouping.
4. Test with values whose answer you already know.
4.2 Example: leap year
A year is a leap year if it is divisible by 4 but not by 100 — unless it is divisible by 400. (Slide L04-S15)
leap.cpp #include <iostream> using namespace std;
int main() { int year; cout << "Enter a year: "; cin >> year;
bool isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
cout << boolalpha << "Leap year: " << isLeap << endl; return 0; } |
year | ÷4 | ÷100 | ÷400 | isLeap |
|---|---|---|---|---|
2024 | yes | no | no | true |
1900 | yes | yes | no | false |
2000 | yes | yes | yes | true |
2026 | no | no | no | false |
4.3 Saying NOT correctly (De Morgan's rule)
When NOT is put in front of brackets, AND becomes OR, OR becomes AND, and each comparison is flipped. (Named after the mathematician Augustus De Morgan.) (Slide L04-S16)
Instead of… | You can write… | Example |
|---|---|---|
!(A && B) | !A || !B | !(age >= 18 && hasCnic) ≡ age < 18 || !hasCnic |
!(A || B) | !A && !B | !(temp < 20 || temp > 30) ≡ temp >= 20 && temp <= 30 |
Comparison | Its opposite |
|---|---|
a < b | a >= b |
a > b | a <= b |
a == b | a != b |
The opposite of < is >=, not > — the value that is equal must go somewhere.
4.4 Short-circuit evaluation
C++ stops checking as soon as the answer is known. (Slide L04-S17)
- With &&: if the left side is false, the right side is not checked (the answer is already false).
- With ||: if the left side is true, the right side is not checked (the answer is already true).
int y = 0; bool ok = (y != 0) && (10 / y > 1); // safe: 10 / y never runs when y is 0 |
Real-world example A guard first checks your university card. If you have no card, he does not even look at the guest list. |
5. Precedence, Traps and the ?: Operator
5.1 Full precedence table so far
(Slide L04-S18)
Priority | Operators |
|---|---|
1 (highest) | ( ) |
2 | ! ++ -- unary - cast |
3 | * / % |
4 | + - |
5 | < <= > >= |
6 | == != |
7 | && |
8 | || |
9 (lowest) | = += -= *= /= %= |
- && is stronger than ||: a || b && c means a || (b && c).
- ! is very strong: !x > 10 means (!x) > 10. Write !(x > 10).
- Arithmetic runs before comparison: a + b == c means (a + b) == c.
5.2 Four traps that compile but give wrong answers
(Slide L04-S19) Compile with warnings switched on (g++ -Wall) — the compiler warns about some of these.
Trap | Wrong code | What really happens | Fix |
|---|---|---|---|
= instead of == | bool full = (marks = 100); | 100 is put into marks; the result is always true | marks == 100 |
Chained comparison | 0 < x < 10 | (0 < x) gives 0 or 1, which is always < 10 | 0 < x && x < 10 |
Short OR | ch == 'a' || 'e' | 'e' on its own is non-zero → always true | ch == 'a' || ch == 'e' |
Comparing doubles | 0.1 + 0.2 == 0.3 | false! decimals are stored approximately | fabs(s - 0.3) < 1e-9 |
traps.cpp (tested) int x = 50; cout << (0 < x < 10); // 1 (true!) — wrong cout << (0 < x && x < 10); // 0 — correct double s = 0.1 + 0.2; cout << (s == 0.3); // 0 — surprising cout << (fabs(s - 0.3) < 1e-9); // 1 — compare with a small tolerance |
5.3 Preview: the conditional operator ?:
The conditional (ternary = three-part) operator chooses one of two values: condition ? valueIfTrue : valueIfFalse. (Slide L04-S20)
cout << (passed ? "PASS" : "FAIL"); int days = isLeap ? 29 : 28; double fee = isStudent ? 50.0 : 100.0; |
Real-world: a cinema ticket costs Rs. 500 for students and Rs. 800 for others: price = isStudent ? 500 : 800;. Full if-else comes in Lecture 7.
6. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
Relational operator | Compares two values: == != < > <= >= |
Condition | An expression whose answer is true or false |
bool | A data type with only two values: true (1) and false (0) |
boolalpha | Manipulator that prints true/false instead of 1/0 |
Logical operator | Joins conditions: && (AND), || (OR), ! (NOT) |
Truth table | A table of every input and the result |
Range check | Testing whether a value is between two limits |
De Morgan's rule | !(A && B) = !A || !B and !(A || B) = !A && !B |
Short-circuit | Stopping the check as soon as the answer is known |
Ternary operator | condition ? a : b — picks a or b |
Tolerance | A very small allowed difference when comparing decimals |
7. Self-Check Questions
1. What is the difference between = and ==? Give an example where using the wrong one causes a bug.
2. Copy and complete the truth table for && and ||.
3. Write a C++ expression: marks are between 0 and 100 inclusive.
4. Why does 0 < x < 10 give true when x = 50?
5. Rewrite !(t < 10 || t > 40) without the !.
6. In (y != 0) && (10 / y > 1), why is there no division-by-zero crash when y = 0?
7. Write the leap-year condition and test it with 1900 and 2000.
Answers are in §2.1, §3.2, §3.4, §5.2, §4.3, §4.4 and §4.2. Homework is on Slide L04-S22.