CT Week 2: Variables & Operators
0. Prerequisites
NOTE
What you need to know:
- Basic Math: BODMAS (Order of operations).
- Logic: True vs False.
Quick Refresher
- Variable: A named storage location.
- Data Types:
- Integer: Whole numbers (1, -5, 0).
- Float: Decimals (3.14, -0.01).
- String: Text (“Hello”, “A”).
- Boolean: True / False.
- Operators:
- Arithmetic:
+,-,*,/. - Relational:
>,<,>=,<=,==(Equal),!=(Not Equal). - Logical:
AND,OR,NOT.
- Arithmetic:
1. Core Concepts
1.1 Assignment vs Equality
- Assignment (
=): “Put value in box”.A = 10(Set A to 10).A = A + 1(Take old A, add 1, put back in A).
- Equality (
==): “Is the content same?“.A == 10(Is A equal to 10? Returns True/False).
1.2 Logical Operators (Truth Tables)
- AND: True only if BOTH are True.
- (True AND True) = True.
- (True AND False) = False.
- OR: True if AT LEAST ONE is True.
- (True OR False) = True.
- (False OR False) = False.
- NOT: Flips the value.
- NOT True = False.
1.3 Precedence (Order of Operations)
- Brackets
() - NOT
- AND
- OR
- Example:
True OR False AND FalseTrue OR (False)True.
- Example:
2. Pattern Analysis & Goated Solutions
Pattern 1: Variable Swapping Logic
Context: “What happens to A and B?” Code:
A = 10
B = 20
T = A
A = B
B = T
TIP
Mental Algorithm (Trace):
- Init: A=10, B=20.
- T = A: T becomes 10.
- A = B: A becomes 20. (Old 10 is gone!).
- B = T: B becomes 10.
- Result: A=20, B=10. (Swapped!).
Pattern 2: Nested Logic (AND/OR Chains)
Context: “Evaluate: (Marks > 90) AND (City == 'Chennai' OR City == 'Bangalore')”
TIP
Mental Algorithm:
- Solve Brackets First: Check the OR part.
- Check Left Side: Check Marks.
- Combine: Apply AND.
- Trap:
Marks > 90 AND City == 'Chennai' OR 'Bangalore'is WRONG. Without brackets, AND happens before OR.
Example (Detailed Solution)
Data: Marks=95, City=“Mumbai”.
Expr: (Marks > 90) AND (City == 'Chennai' OR City == 'Bangalore')
Trace:
Marks > 90True.City == 'Chennai'False.City == 'Bangalore'False.False OR FalseFalse.True AND FalseFalse. Answer: False.
Pattern 3: The “Update” Pattern (A = A + X)
Context: “What is the final value of Sum?” Code:
Sum = 0
Sum = Sum + 10
Sum = Sum + 20
TIP
Mental Algorithm:
- Right Side First: Calculate the value on the right of
=.- Update Left: Store result in the variable.
- Step 1:
0 + 10 = 10. Sum becomes 10.- Step 2:
10 + 20 = 30. Sum becomes 30.
3. Practice Exercises
- Logic:
NOT (True OR False)?- Hint:
True OR Falseis True.NOT Trueis False.
- Hint:
- Assignment:
A = 5.B = A + 2.A = 10. Value of B?- Hint: B was calculated when A was 5. So B=7. Changing A later doesn’t change B.
- Type: Result of
10 / 2?- Hint: In many systems, division returns a Float (5.0). In CT pseudocode, usually just 5.