CT Week 8: Procedures & Advanced Logic

1. The Power of Procedures

As our logic gets more complex, writing everything in one giant while loop becomes messy and error-prone. Procedures (functions) allow us to break code into smaller, reusable blocks.

Syntax

Procedure ProcedureName(Parameter1, Parameter2)
    # Body of the procedure
    # ... logic ...
    return(Result)
End ProcedureName

Key Concepts

  1. Parameters (Inputs): Variables passed into the procedure.
  2. Return Value (Output): The result sent back to the main code.
  3. Call: Executing the procedure, e.g., X = ProcedureName(A, B).

2. Modular Programming Pattern

Goal: Solve a big problem by solving small sub-problems.

Example: Find the student with the highest average marks. Breakdown:

  1. Procedure CalculateAverage(MarksList) → Returns a number.
  2. Main Code: Loop through students, call CalculateAverage for each, compare to find max.

Pseudocode:

Procedure GetAvg(M, P, C)
    total = M + P + C
    return(total / 3)
End GetAvg
 
# Main Code
maxAvg = 0
while(Table 1 has more rows){
    Read row X
    avg = GetAvg(X.Math, X.Physics, X.Chem) # Call
    if(avg > maxAvg){
        maxAvg = avg
    }
    Move X to Table 2
}

3. Procedures with Dictionaries

We can pass dictionaries to procedures or return them.

Pattern: Dictionary Builder Procedure

Goal: A procedure that takes a list and returns a frequency dictionary.

Procedure BuildFreqDict(WordList)
    D = {}
    foreach w in WordList{
        if(w in D){
            D[w] = D[w] + 1
        }
        else{
            D[w] = 1
        }
    }
    return(D)
End BuildFreqDict

Pattern: Dictionary Query Procedure

Goal: A procedure that checks a condition using a dictionary.

Procedure IsAllMedals(PlayerID, MedalDict)
    # MedalDict maps PlayerID to a list of medals won
    if(PlayerID in MedalDict){
        medals = MedalDict[PlayerID]
        if("Gold" in medals and "Silver" in medals and "Bronze" in medals){
            return(True)
        }
    }
    return(False)
End IsAllMedals

4. Advanced Trace Table: Scope & State

Crucial Concept: Variables inside a procedure are usually local. Changing x inside a procedure doesn’t change x outside unless it’s returned or a global structure (like a list/dict passed by reference) is modified.

Trace Example:

Procedure Update(val)
    val = val + 10
    return(val)
End Update
 
A = 5
B = Update(A)
# At this point:
# A is still 5 (passed by value logic in simple variables)
# B is 15

Trace Example (Mutable List/Dict): Note: In CT pseudocode, assume lists/dicts are passed by reference (changes stick) unless specified otherwise.

Procedure AddItem(L)
    L = L ++ [99] # Modifies the list
    return(L)
End AddItem
 
MyList = [1, 2]
AddItem(MyList)
# MyList becomes [1, 2, 99]

5. Common Week 8 Algorithms

5.1 The “Filter and Count” Procedure

(Seen in Q69 “CountVowels”)

  1. Main Loop: Iterates through dataset.
  2. Helper Procedure: Checks a specific complex condition (e.g., CountVowels(word) >= 3).
  3. Action: If Helper returns True, increment Main Counter.

5.2 The “Top K” Finder

  1. Step 1: Build a Dictionary of Student -> TotalMarks.
  2. Step 2: Convert Dictionary to List of Pairs.
  3. Step 3: Sort List (or find Max repeatedly).
  4. Step 4: Extract Top K.

6. Summary Checklist

  • Define Procedure: Procedure Name(Args)... End.
  • Call Procedure: Val = Name(Inputs).
  • Return: Passes value back.
  • Scope: Be careful with variable names inside vs outside.
  • Modularity: Use procedures to hide complexity (e.g., isPrime(x) instead of writing the loop every time).

đź§  Level Up: Advanced Practice

Question 1: Procedure Side Effects

Problem: Procedure Update(L) appends 5 to list L.

  • Call Update(MyList).
  • Does MyList change outside? Answer: Yes. Lists are usually passed by reference (mutable). Contrast: If Update(x) changes integer x, the original x usually doesn’t change (passed by value).

Question 2: Modular Design

Problem: Write a procedure IsPrime(n). Logic:

Procedure IsPrime(n):
    If n < 2 Return False
    For i = 2 to sqrt(n):
        If (n % i == 0) Return False
    Return True
End Procedure

Usage: If IsPrime(X) then .... Cleaner code.

Question 3: Return vs Print

Problem: Difference between Return X and Print X. Answer:

  • Return: Passes value back to caller. Can be used in calculations (A = 5 + GetVal()).
  • Print: Shows to user. Cannot be used by program logic.