Week 2: Iteration & Filtering
2188 words
11 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Week 2: Iteration & Filtering > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Topic 03 (Pseudocode Basics) **Cross-links:** BSCS1002-Python (Week 2 — Loops, Conditions) ## 1. Motivation: Beyond Simple Counting In Topic 01, we learned that iteration means "doing something repeatedly." But what exactly can w...

Week 2: Iteration & Filtering
BSCS1001 — IIT Madras BS Degree Prerequisite: Topic 03 (Pseudocode Basics) Cross-links: BSCS1002-Python (Week 2 — Loops, Conditions)
1. Motivation: Beyond Simple Counting
In Topic 01, we learned that iteration means "doing something repeatedly." But what exactly can we do repeatedly?
Three fundamental operations form the backbone of almost every algorithm:
| Operation | Description | Analogy |
|---|---|---|
| Count | How many items? | Counting students in a class |
| Sum | Add up values | Total marks of all students |
| Max/Min | Find extreme values | Who scored highest? |
These may seem simple, but they are the building blocks of sophisticated data analysis.
💡 Key Insight: The difference between counting, summing, and finding max is just what you do inside the loop. The iteration structure is the same.
2. The Two Core Patterns
Pattern A: Accumulation (Count, Sum)
In accumulation, the variable's new value depends on its previous value plus something new.
pseudoVariable = Variable + NewValue
Examples:
Count = Count + 1(add 1 each time)Sum = Sum + X.Maths(add current value each time)
Pattern B: Tracking (Max, Min)
In tracking, the variable's new value might be replaced if the current item is more extreme.
pseudoif (X.Value > Variable) { Variable = X.Value }
Examples:
if (X.Maths > Max) { Max = X.Maths }(update max)if (X.Maths < Min) { Min = X.Maths }(update min) (Diagram)
3. Finding Maximum: The Tracker Pattern
The Algorithm
sqlMax = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Maths > Max) { Max = X.Maths } }
How It Works
- Initialize Max to a very small value (0 if marks are non-negative)
- For each card, compare X.Maths with current Max
- If X.Maths is larger, update Max
- After processing all cards, Max holds the largest value
Flowchart
(Diagram)
Tracing: Find Maximum Marks
Dataset: [45, 78, 62, 91, 53]
| Iter | X.Maths | Max Before | Condition (X > Max?) | Max After |
|---|---|---|---|---|
| 1 | 45 | 0 | 45 > 0 ✅ Yes | 45 |
| 2 | 78 | 45 | 78 > 45 ✅ Yes | 78 |
| 3 | 62 | 78 | 62 > 78 ❌ No | 78 |
| 4 | 91 | 78 | 91 > 78 ✅ Yes | 91 |
| 5 | 53 | 91 | 53 > 91 ❌ No | 91 |
Result: Maximum = 91
What If All Values Are Negative?
If
Max = 0 but all marks are negative (e.g., [-5, -10, -3]), the algorithm incorrectly returns 0.
Solution: Initialize Max to the first card's value instead:sqlMax = 0 FirstCard = True while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (FirstCard) { Max = X.Maths FirstCard = False } else if (X.Maths > Max) { Max = X.Maths } }
4. Finding Max with Card ID
Often we need to know which student has the max marks, not just the value.
The Algorithm
sqlMaxM = 0 MaxCard = -1 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Maths > MaxM) { MaxM = X.Maths MaxCard = X.Id } }
Tracing
Dataset:
| Card ID | Name | Maths |
|---|---|---|
| 101 | Alice | 85 |
| 102 | Bob | 92 |
| 103 | Charlie | 78 |
| 104 | Diana | 95 |
| Iter | X.Id | X.Maths | MaxM Before | Condition | MaxM After | MaxCard |
|---|---|---|---|---|---|---|
| 1 | 101 | 85 | 0 | 85>0 ✅ | 85 | 101 |
| 2 | 102 | 92 | 85 | 92>85 ✅ | 92 | 102 |
| 3 | 103 | 78 | 92 | 78>92 ❌ | 92 | 102 |
| 4 | 104 | 95 | 92 | 95>92 ✅ | 95 | 104 |
Result: Max = 95, achieved by student ID = 104 (Diana)
Why Initialize MaxCard to -1?
- Card IDs are typically positive numbers (e.g., 1, 2, 3, ...)
-1is an impossible card ID, serving as "no card selected yet"- If MaxCard remains -1 after the loop, the dataset was empty
5. Finding Both Max and Min
We can find both in a single pass:
sqlMax = -INFINITY Min = INFINITY while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Maths > Max) { Max = X.Maths } if (X.Maths < Min) { Min = X.Maths } }
Tracing
Dataset: [45, 78, 62, 91, 53]
| Iter | X | Max Before | Max After | Min Before | Min After |
|---|---|---|---|---|---|
| 1 | 45 | -∞ | 45 | ∞ | 45 |
| 2 | 78 | 45 | 78 | 45 | 45 |
| 3 | 62 | 78 | 78 | 45 | 45 |
| 4 | 91 | 78 | 91 | 45 | 45 |
| 5 | 53 | 91 | 91 | 45 | 53? No, 45 < 53 so Min stays 45 |
Result: Max = 91, Min = 45
Note: Two separateifstatements (notif-else) because a single card could be both new max AND new min (if it's the first card).
6. The AND Operator in Filters
Compound Conditions
The AND operator combines two conditions — both must be True for the combined condition to be True.
AND Truth Table
| Condition 1 | Condition 2 | C1 AND C2 |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
Using AND in Filtering
sqlCount = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Gender == "M" AND X.Maths > 80) { Count = Count + 1 } }
This counts boys who scored above 80 in Maths.
Worked Example: AND Filter
Dataset:
| Name | Gender | Maths |
|---|---|---|
| Alice | F | 90 |
| Bob | M | 85 |
| Charlie | M | 72 |
| Diana | F | 78 |
| Ethan | M | 95 |
Filter:
X.Gender == "M" AND X.Maths > 80| Card | Gender | Maths | Gender=="M"? | Maths>80? | AND | Increment? |
|---|---|---|---|---|---|---|
| Alice | F | 90 | No | Yes | No | ❌ |
| Bob | M | 85 | Yes | Yes | Yes | ✅ Count=1 |
| Charlie | M | 72 | Yes | No | No | ❌ |
| Diana | F | 78 | No | No | No | ❌ |
| Ethan | M | 95 | Yes | Yes | Yes | ✅ Count=2 |
Result: Count = 2 (Bob and Ethan)
Comparison: AND vs Sequential Ifs
(Diagram)
Both forms are equivalent. AND is more compact.
7. Accumulation through Iteration
Accumulation is the process of building up a value step by step during iteration.
Types of Accumulators
| Accumulator | Initial Value | Update Rule | Example |
|---|---|---|---|
| Counter | 0 | Count = Count + 1 | Number of students |
| Sum | 0 | Sum = Sum + X.Value | Total marks |
| Product | 1 | Prod = Prod × X.Value | (Rare in this course) |
| List builder | [] | List = List ++ [X] | Collecting items (Week 5) |
Combining Accumulation with Filtering
We can accumulate while filtering:
sqlTotalBoysMaths = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Gender == "M") { TotalBoysMaths = TotalBoysMaths + X.Maths } }
This is accumulation with filtering — one of the most common patterns in the course.
Multiple Accumulators
We can track multiple things in a single pass:
sqlBoySum = 0 GirlSum = 0 BoyCount = 0 GirlCount = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Gender == "M") { BoySum = BoySum + X.Maths BoyCount = BoyCount + 1 } else { GirlSum = GirlSum + X.Maths GirlCount = GirlCount + 1 } } BoyAvg = BoySum / BoyCount GirlAvg = GirlSum / GirlCount
This computes the average Maths marks for boys and girls separately in a single pass!
8. Comparison: Iteration Patterns
Summary Table
| Pattern | Initial Value | Update Condition | Update Action | Use Case |
|---|---|---|---|---|
| Count | 0 | Always (every card) | Count = Count + 1 | How many? |
| Sum | 0 | Always (or with filter) | Sum = Sum + X.Value | Total? |
| Average | Sum=0, Count=0 | Always | Sum+=X, Count+=1 | What's typical? |
| Max | 0 or -∞ | When X > Max | Max = X.Value | Best score? |
| Min | ∞ | When X < Min | Min = X.Value | Worst score? |
| Max with ID | Max=0, ID=-1 | When X > Max | Max = X.Value; ID = X.Id | Who scored best? |
Decision Tree: Which Pattern?
(Diagram)
9. Practice Questions
Basic Questions
Q1. Trace the max-finding algorithm for dataset [12, 45, 7, 38, 22].
Show Answer
| Iter | X | Max Before | X > Max? | Max After |
|---|---|---|---|---|
| 1 | 12 | 0 | 12>0 ✅ | 12 |
| 2 | 45 | 12 | 45>12 ✅ | 45 |
| 3 | 7 | 45 | 7>45 ❌ | 45 |
| 4 | 38 | 45 | 38>45 ❌ | 45 |
| 5 | 22 | 45 | 22>45 ❌ | 45 |
Max = 45 Q2. What does this pseudocode output for dataset [3, 8, 1, 6]?
sqlResult = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X > Result) { Result = X } }
Show Answer
| Iter | X | X > Result? | Result |
|---|---|---|---|
| 1 | 3 | 3 > 0 ✅ | 3 |
| 2 | 8 | 8 > 3 ✅ | 8 |
| 3 | 1 | 1 > 8 ❌ | 8 |
| 4 | 6 | 6 > 8 ❌ | 8 |
Result = 8 (the maximum) Q3. Write pseudocode to find the minimum value (instead of maximum). Show AnswersqlMin = INFINITY // A very large number while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X < Min) { Min = X } }
Q4. Evaluate these AND conditions: (a)
True AND False (b) True AND True (c) False AND False (d) (5 > 3) AND (10 < 20)Show Answer
| Expression | Step 1 | Step 2 | Result |
|---|---|---|---|
True AND False | — | — | False |
True AND True | — | — | True |
False AND False | — | — | False |
(5>3) AND (10<20) | True AND True | — | True |
Intermediate Questions
Q5. Write pseudocode to find the student with the minimum marks in Physics (return both the marks and the student ID).
Show AnswersqlMinPhy = INFINITY MinCard = -1 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Physics < MinPhy) { MinPhy = X.Physics MinCard = X.Id } }
Q6. What is the difference between these two code snippets?
Snippet A:
pseudoif (X.Gender == "M") { if (X.Maths > 80) { Count = Count + 1 } }
Snippet B:
pseudoif (X.Gender == "M" AND X.Maths > 80) { Count = Count + 1 }
Show AnswerThey are equivalent. Both count boys who scored above 80. Snippet A uses nestedifstatements, Snippet B uses a compound condition withAND. The result is identical. Q7. Trace this pseudocode. What does it compute?
sqlResult = 0 Count = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X > 0) { Result = Result + X Count = Count + 1 } } Result = Result / Count
For dataset: [-5, 10, 0, 20, -3, 15]
Show Answer
| Iter | X | X > 0? | Result | Count |
|---|---|---|---|---|
| 1 | -5 | ❌ | 0 | 0 |
| 2 | 10 | ✅ | 10 | 1 |
| 3 | 0 | ❌ (not >0) | 10 | 1 |
| 4 | 20 | ✅ | 30 | 2 |
| 5 | -3 | ❌ | 30 | 2 |
| 6 | 15 | ✅ | 45 | 3 |
Final:Result = 45 / 3 = **15**It computes the average of positive numbers. Q8. The following algorithm has a bug. Find and fix it.
sqlMax = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (Max > X.Maths) { Max = X.Maths } }
Show AnswerBug: The condition is reversed!if (Max > X.Maths)updates Max when the current Max is greater than X.Maths, which would track the minimum, not the maximum.Fix: Change toif (X.Maths > Max).Also, if all values could be negative, initialize Max to the first value or -INFINITY.
Advanced Questions
Q9. Write pseudocode to find the second highest value in a dataset.
Show AnswersqlMax = 0 SecondMax = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X > Max) { SecondMax = Max Max = X } else if (X > SecondMax) { SecondMax = X } }Logic:
When we find a new maximum, the old maximum becomes the second maximum Otherwise, check if X beats the current second maximum Q10. Trace the second-max algorithm for dataset [10, 30, 20, 50, 40]. Show Answer
| Iter | X | Before: Max, SecMax | Action | After: Max, SecMax |
|---|---|---|---|---|
| 1 | 10 | 0, 0 | X > Max → SecMax=0, Max=10 | 10, 0 |
| 2 | 30 | 10, 0 | X > Max → SecMax=10, Max=30 | 30, 10 |
| 3 | 20 | 30, 10 | X not > Max, X > SecMax (20>10) → SecMax=20 | 30, 20 |
| 4 | 50 | 30, 20 | X > Max → SecMax=30, Max=50 | 50, 30 |
| 5 | 40 | 50, 30 | X not > Max, X > SecMax (40>30) → SecMax=40 | 50, 40 |
Result: Max = 50, SecondMax = 40 Q11. Write pseudocode that counts how many times each of the values "High", "Medium", "Low" appears in a dataset (but without using dictionaries — just three counters). Show AnswersqlHighCount = 0 MedCount = 0 LowCount = 0 while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Category == "High") { HighCount = HighCount + 1 } else if (X.Category == "Medium") { MedCount = MedCount + 1 } else if (X.Category == "Low") { LowCount = LowCount + 1 } }
Q12. Design an algorithm that finds both the maximum Maths mark AND which gender achieved it. You need to track the maximum and the gender of the student who achieved it.
Show AnswersqlMaxM = -1 MaxGender = "" while (Pile 1 has more cards) { Pick a card X from Pile 1 Move X to Pile 2 if (X.Maths > MaxM) { MaxM = X.Maths MaxGender = X.Gender } } // Now MaxGender tells us if a boy or girl topped MathsTrace with data:
| Card | Gender | Maths | Action | MaxM | MaxGender |
|---|---|---|---|---|---|
| 1 | F | 85 | New max | 85 | F |
| 2 | M | 92 | New max | 92 | M |
| 3 | M | 78 | No | 92 | M |
| 4 | F | 95 | New max | 95 | F |
Result: Max = 95, achieved by a Female student.
📚 Cross-References
| Course | Topic | Connection |
|---|---|---|
| BSCS1002 (Python) | Week 2 — Loops | Python for and while loops |
| BSCS1002 (Python) | Week 3 — Conditions | Python if, elif, else |
| BSCS2002 (PDSA) | Week 2 — Max/Min | Formal algorithm analysis |
Next Topic: 05 — Procedures & ParametersQuiz Tip: Single-iteration max/min problems are the most common type in Quiz 1. Practice tracing until it's automatic! Join Discord PreviousPseudocode BasicsNextProcedures & Parameters