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.

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)

  1. AND: True only if BOTH are True.
    • (True AND True) = True.
    • (True AND False) = False.
  2. OR: True if AT LEAST ONE is True.
    • (True OR False) = True.
    • (False OR False) = False.
  3. NOT: Flips the value.
    • NOT True = False.

1.3 Precedence (Order of Operations)

  1. Brackets ()
  2. NOT
  3. AND
  4. OR
    • Example: True OR False AND False True OR (False) True.

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):

  1. Init: A=10, B=20.
  2. T = A: T becomes 10.
  3. A = B: A becomes 20. (Old 10 is gone!).
  4. B = T: B becomes 10.
  5. 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:

  1. Solve Brackets First: Check the OR part.
  2. Check Left Side: Check Marks.
  3. 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:

  1. Marks > 90 True.
  2. City == 'Chennai' False.
  3. City == 'Bangalore' False.
  4. False OR False False.
  5. True AND False False. 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:

  1. Right Side First: Calculate the value on the right of =.
  2. 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

  1. Logic: NOT (True OR False)?
    • Hint: True OR False is True. NOT True is False.
  2. 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.
  3. Type: Result of 10 / 2?
    • Hint: In many systems, division returns a Float (5.0). In CT pseudocode, usually just 5.