CT Week 3: Conditionals (Decision Making)
0. Prerequisites
NOTE
What you need to know:
- Relational Operators: .
- Logical Operators: AND, OR, NOT.
Quick Refresher
- If Statement: Executes code only if condition is True.
- Else: Executes code if the condition is False.
- Nested If: An
ifinside anotherif.
1. Core Concepts
1.1 The Structure
- Simple If:
If (Condition) { Do Something } - If-Else:
If (Condition) { Do A (True Path) } Else { Do B (False Path) } - If-Else If-Else (Ladder):
- Checks conditions one by one.
- Crucial: As soon as one matches, it executes that block and skips the rest.
1.2 Independent vs Mutually Exclusive
- Series of Ifs (Independent):
If A > 10 ...If A > 20 ...- Result: Both can run.
- If-Else If (Mutually Exclusive):
If A > 10 ...Else If A > 20 ...- Result: Only the first one runs.
2. Pattern Analysis & Goated Solutions
Pattern 1: The “Ladder” Trap (First Match Wins)
Context: “What is printed?” Code:
Marks = 95
If Marks > 35:
Print "Pass"
Else If Marks > 90:
Print "Grade A"
TIP
Mental Algorithm:
- Check 1st Condition:
95 > 35? Yes.- Execute: Print “Pass”.
- Skip Rest: The
Else Ifis IGNORED because the firstIfwas taken.
- Fix: Always order from Specific (High) to General (Low). Check
>90first.
Pattern 2: Nested Logic (The “And” Equivalent)
Context: “When does X become 1?” Code:
If City == "Chennai":
If Gender == "F":
X = 1
TIP
Mental Algorithm:
- Translate to Logic: Nested Ifs are equivalent to AND.
- Condition:
City == "Chennai" AND Gender == "F".
Pattern 3: Finding the “Else” Owner
Context: “Which ‘If’ does this ‘Else’ belong to?” Code:
If A:
If B:
Print "X"
Else:
Print "Y"
TIP
Mental Algorithm:
- Indentation: Look at the alignment.
- Matching: The
Elsebelongs to theIfat the same indentation level.
- Here,
ElsematchesIf A.- So “Y” prints only if
Ais False.
3. Practice Exercises
- Logic:
If TruethenIf FalsethenPrint AelsePrint B. Output?- Hint: Outer True enters. Inner False goes to Else. Prints B.
- Ladder:
X=10.If X>5: A=1.If X>8: A=2. Final A?- Hint: These are separate Ifs (not Else If). Both run. A becomes 1, then A becomes 2. Final 2.
- Trace:
X=5.If X>10: Y=1 Else: Y=2. Final Y?- Hint: is False. Goes to Else. Y=2.
🧠 Level Up: Advanced Practice
Question 1: Modulo & Logic
Problem:
If (LetterCount % 2 == 0) { P = P + 1 }
Else {
If (PartOfSpeech == "Adverb") { Q = Q + 1 }
}Interpretation:
Pcounts words with Even letter count.Qcounts Adverbs that have Odd letter count (since they fell into theElseblock).
Question 2: The “At Least One” Condition
Problem: Count students who scored < 80 in at least one subject. Logic:
If (Math < 80) OR (Phy < 80) OR (Chem < 80) then Count = Count + 1. Contrast: “In exactly two subjects” would require:((M<80) + (P<80) + (C<80)) == 2. (Treating True as 1).
Question 3: Nested vs Chained
Scenario:
- Nested:
If A { If B { ... } }→ Requires A AND B. - Chained:
If A { ... } Else If B { ... }→ Checks B only if A is False. Trap: Using Chained when you want to check both independently.