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 ProcedureNameKey Concepts
- Parameters (Inputs): Variables passed into the procedure.
- Return Value (Output): The result sent back to the main code.
- 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:
- Procedure
CalculateAverage(MarksList)→ Returns a number. - Main Code: Loop through students, call
CalculateAveragefor 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 BuildFreqDictPattern: 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 IsAllMedals4. 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 15Trace 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”)
- Main Loop: Iterates through dataset.
- Helper Procedure: Checks a specific complex condition (e.g.,
CountVowels(word) >= 3). - Action: If Helper returns True, increment Main Counter.
5.2 The “Top K” Finder
- Step 1: Build a Dictionary of
Student -> TotalMarks. - Step 2: Convert Dictionary to List of Pairs.
- Step 3: Sort List (or find Max repeatedly).
- 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
MyListchange outside? Answer: Yes. Lists are usually passed by reference (mutable). Contrast: IfUpdate(x)changes integerx, the originalxusually 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 ProcedureUsage: 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.