Computational Thinking - Week 3: Procedures and Nested Logic
Core Idea: This week, we introduce a powerful organizational tool: procedures (also known as functions or subroutines). We learn how to break down a large problem into smaller, reusable tasks. We also explore more complex logical structures, such as nested loops and boolean logic, which allow us to answer highly specific questions about our data.
A procedure is a named block of instructions that performs a specific task. Think of it as a mini-algorithm that you can “call” whenever you need it. This helps to avoid repeating code and makes the main algorithm easier to read.
Defining a Procedure: A procedure has a name, accepts inputs (called parameters or arguments), and can produce an output (a return value).
Procedure CalculateAverage(Card_Pile): // Instructions to calculate the average of Card_Pile ... Return the calculated average
Calling a Procedure: To use a procedure, you “call” it by its name and provide the necessary inputs.
// In the main algorithm:Avg_Chennai = CalculateAverage(Chennai_Pile)Avg_Vellore = CalculateAverage(Vellore_Pile)
Here, we reuse the same CalculateAverage logic on different piles of cards.
🔄 1.2 Nested Iteration (Loop within a Loop)
So far, we’ve iterated through one pile of cards. Nested iteration means that for each card in an outer loop, we iterate through another entire pile of cards in an inner loop. This pattern is essential for comparing every card with every other card.
The “Handshake” Analogy: Imagine you are in a room of people (Pile 1). You (the outer loop) want to shake hands with everyone.
You pick one person, Person_X.
Now, you iterate through everyone else in the room (Person_Y in Pile 2) and shake their hand.
Once you’ve shaken everyone’s hand, you are “done” with Person_X, and you move on to the next person in the outer loop.
Pseudocode Structure:
// Outer loopWhile Pile 1 is not empty: Read card X from Pile 1 // Inner loop While Pile 2 is not empty: Read card Y from Pile 2 // Compare X and Y ... Move Y to Pile 3 // After inner loop finishes, restore Pile 2 for the next outer loop iteration Move all cards from Pile 3 back to Pile 2 Move X to a final discard pile
This pattern is used for finding duplicates, pairs, or any task that requires all-to-all comparisons.
đź§ 1.3 Boolean Logic and Flags
Boolean Variable (Flag): A variable that can only hold one of two values: True or False. It acts like a switch or a flag to remember if a certain event has occurred.
Common Use Case: The “Universal Quantifier” (For All)
How do you check if all students passed? You can’t know until you’ve seen every card.
Assume the best: Initialize a flag All_Passed to True.
Look for a single failure: Loop through the cards. If you find even one student who failed, you immediately change the flag: Set All_Passed = False.
Check the flag at the end: After the loop, if All_Passed is still True, it means you never found a failure, so the condition holds for everyone.
Common Use Case: The “Existential Quantifier” (At Least One)
How do you check if at least one student is from Chennai?
Assume the worst: Initialize a flag Found_Chennai to False.
Look for a single success: Loop through the cards. If you find a student from Chennai, set Found_Chennai = True and you can often stop looking.
2. Question Pattern Analysis
From the Week_3_Graded_Assignment, these are the key patterns.
Pattern #
Pattern Name
Frequency
Difficulty
Core Skill
3.1
Boolean Logic with Flags
High
Medium
Interpreting procedures that use True/False flags to check for “all” or “at least one”.
3.2
Using Procedures (Subroutines)
High
Medium-Hard
Understanding how a main algorithm calls a helper procedure with different parameters.
3.3
Interpreting Complex Nested Conditions
Medium
Medium
Tracing logic that involves multiple If/Else statements to count specific subgroups.
3.4
Bug Identification in Procedures/Logic
Medium
Medium
Finding errors in the initialization of flags or the logic within a procedure.
3. Detailed Solutions by Pattern
Pattern 3.1: Boolean Logic with Flags
Core Skill: Recognizing the “assume the best, look for one failure” pattern for “all” and the “assume the worst, look for one success” pattern for “at least one”.
Example Problem:
The following pseudocode is executed on the “Scores” dataset. What does it mean if E is True at the end?
Initialize E to TrueWhile Pile 1 is not empty: Read card X If X.Gender is "F" then If X.Physics < 60 OR X.Chemistry < 60 OR X.Maths < 60 then Set E to False Move X to Pile 2
TAA in Action:
Triage: I see a variable E initialized to True and only ever set to False. This is a “for all” check.
Abstract: The procedure assumes a positive outcome (E=True) and only changes its mind if it finds a single piece of contradictory evidence. The condition to set E to False is: “a female student has a score less than 60 in at least one subject”.
Act:
The flag E will remain True only if the condition Set E to False is never triggered.
This means that for every female student, the condition X.Physics < 60 OR X.Chemistry < 60 OR X.Maths < 60 must be false.
The opposite of “at least one score is < 60” is “all scores are >= 60”.
Therefore, E will be True at the end if all female students have scores greater than or equal to 60 in Physics, Chemistry, and Maths.
Final Answer: All female students have scores greater than or equal to 60 in Physics, Chemistry and Maths.
Pattern 3.2: Using Procedures (Subroutines)
Core Skill: Following the flow of control as the main algorithm passes data to a procedure and gets a result back.
Example Problem:
At the end of the main procedure, A represents the number of students from Madurai whose total marks are greater than the average marks of students from Vellore but less than the average of students from Chennai. avg(P) is a procedure that calculates the average total marks of a given pile P.
// (Assume piles Madurai_Pile, Vellore_Pile, Chennai_Pile are created)Vellore_Avg = avg(Vellore_Pile)Chennai_Avg = avg(Chennai_Pile)Initialize A to 0While Madurai_Pile is not empty: Read card X from Madurai_Pile If X.Total > Vellore_Avg AND X.Total < Chennai_Avg then Increment A
TAA in Action:
Triage: The code uses a procedure avg() and then uses its results. This is a procedure-based problem.
Abstract: The logic is straightforward. First, calculate the averages for Vellore and Chennai. Then, iterate through the Madurai students and count how many fall between these two calculated averages.
Act:
Vellore_Avg will hold the average total marks for all students from Vellore.
Chennai_Avg will hold the average total marks for all students from Chennai.
The If statement directly checks if a Madurai student’s total is greater than Vellore’s average AND less than Chennai’s average.
A counts the number of times this condition is true.
Final Answer:A represents the number of students from Madurai having total marks greater than the average marks of students from Vellore but less than that of Chennai.
Memory Palace: Week 3 Concepts
Procedures (The Specialist):
Imagine your main algorithm is a general contractor building a house. When it’s time for the electrical work, the contractor doesn’t do it themselves. They call a specialist (the electrician/procedure).
They give the specialist the blueprints (parameters).
The specialist does their job and reports back when they’re done (returns a value).
The contractor can then call the same electrician for a different house (reusability).
Nested Loops (The Class Photo):
You want to find every pair of students in a class who are wearing the same color shirt.
Outer Loop: You are Student X. You stand still.
Inner Loop: Your friend, Student Y, walks down the line, comparing their shirt color to yours. They do this for every other student.
Once your friend is done, you go to the end of the line, and the next person becomes the new Student X. This repeats until every pair has been checked.
Boolean Flags (The Detective):
A detective is trying to prove a suspect is guilty. The suspect’s claim is “I have never been to the crime scene”.
The detective’s flag, Suspect_Is_Lying, is initialized to False.
The detective loops through all the evidence (the cards).
If they find just one piece of evidence—a single fingerprint, a security camera photo (If evidence found then...)—they flip the flag to True (Set Suspect_Is_Lying = True) and can stop looking.
If the flag is still False at the end, it means the suspect’s claim might be true. This is the “at least one” pattern.