Week 2: Iteration, Filtering & Selection
3508 words
18 min read
2026-09-12T00:00:00.000Z
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
Iterating over datasets, tracking state, accumulator patterns, finding maximum/minimum values, and the AND operator. # Computational Thinking — Week 2: Iteration, Filtering & Selection IITM’s CT Week 2 covers **Iteration, Filtering, Selection, Pseudocode, Finding Maximum and Minimum, and the AND operator**.

Computational Thinking — Week 2: Iteration, Filtering & Selection
IITM’s CT Week 2 covers Iteration, Filtering, Selection, Pseudocode, Finding Maximum and Minimum, and the AND operator.
TL;DR
Week 1 gave the basic loop structure.
Week 2 adds decision-making inside loops.
The core pattern becomes:
textinitialize state for each item: check conditions selectively update state output result
The highest-value ideas are:
- iteration = repeatedly process data
- filtering = decide which items matter
- selection = choose what action to take based on conditions
- pseudocode = language-independent algorithm description
- maximum/minimum = keep track of the best value seen so far
AND= multiple conditions must all be true
1. Iteration recap
Iteration means repeatedly executing the same logical steps.
Example:
textfor each x in data: process x
If:
textdata = [4, 7, 2]
then the body executes three times.
2. Iteration over a dataset
Suppose:
textmarks = [45, 72, 88, 39]
A loop conceptually behaves like:
textx = 45 x = 72 x = 88 x = 39
one after another.
3. State during iteration
An algorithm usually maintains some state.
Example:
textcount = 0
Then while scanning the data:
textcount = count + 1
when required.
The current state summarizes what has happened so far.
4. Filtering
Filtering means:
process only the items satisfying a condition.
Example:
textfor each x: if x > 50: process x
All other values are ignored.
5. Example
Data:
text20, 60, 75, 30, 90
Filter:
textx > 50
Selected values:
text60, 75, 90
6. Filter + count
Suppose we want:
number of students with marks above 50.
Pseudocode:
textcount = 0 for each mark: if mark > 50: count = count + 1
For:
text20, 60, 75, 30, 90
output:
7. Filter + sum
Suppose we want:
sum of only positive values.
texttotal = 0 for each x: if x > 0: total = total + x
For:
text-3, 5, 7, -1
output:
8. Selection
Selection means choosing between different actions based on conditions.
Basic form:
textif condition: action A else: action B
So iteration answers:
repeat?
Selection answers:
which branch?
9. Example
textif mark >= 40: result = "Pass" else: result = "Fail"
Only one branch executes.
10. Multiple-way selection
Sometimes there are several cases.
Example:
textif mark >= 90: grade = "A" else if mark >= 75: grade = "B" else if mark >= 60: grade = "C" else: grade = "D"
The order of conditions matters.
11. Why order matters
Suppose:
textmark = 95
If you test:
textmark >= 60
first and stop there, you might incorrectly classify it as just the lowest passing grade.
So selection logic should usually test more specific/higher-priority cases first.
12. Iteration + selection
Most real algorithms combine both.
Example:
textcount = 0 for each mark: if mark >= 50: count = count + 1
Loop:
- visits every mark
Selection:
- decides whether to increment
13. Pseudocode
Pseudocode describes an algorithm without committing to a specific programming language.
Example:
texttotal = 0 for each number x in data: total = total + x print total
The goal is logic, not syntax.
14. Why pseudocode is useful
It lets you focus on:
- state
- conditions
- iteration
- sequence
- correctness
without worrying about:
- Python syntax
- semicolons
- indentation rules of a specific language
- libraries
15. Reading pseudocode
You should read pseudocode literally and sequentially.
Example:
textx = 5 x = x + 2 x = x * 3
Trace:
Final:
16. Trace tables
A trace table is one of the best tools in CT.
Example:
texts = 0 for each x in [2, 4, 1]: s = s + x
| Step | x | s before | s after |
|---|---|---|---|
| start | — | — | 0 |
| 1 | 2 | 0 | 2 |
| 2 | 4 | 2 | 6 |
| 3 | 1 | 6 | 7 |
Final:
17. Finding a maximum
Suppose we have:
text4, 9, 2, 11, 6
We want the largest value.
A standard pattern is:
textmax = first value for each remaining value x: if x > max: max = x
18. Maximum trace
Data:
text4, 9, 2, 11, 6
Initialize:
textmax = 4
Then:
x | Current max | x > max? | New max |
|---|---|---|---|
| 9 | 4 | Yes | 9 |
| 2 | 9 | No | 9 |
| 11 | 9 | Yes | 11 |
| 6 | 11 | No | 11 |
Final:
19. Maximum invariant
During the loop:
maxis the largest value among all items processed so far.
That is the key mental model.
20. Finding a minimum
Same idea:
textmin = first value for each remaining value x: if x < min: min = x
21. Minimum example
Data:
text8, 5, 12, 3, 9
Trace:
textmin = 8
then:
Final:
22. Why initialize max/min to first value
This is safer than using arbitrary values.
Suppose all numbers are negative:
text-10, -5, -20
If you initialize:
textmax = 0
then algorithm may wrongly return:
even though 0 is not in the data.
Correct:
textmax = first value
23. Bad maximum initialization
Wrong:
textmax = 0
for arbitrary numerical data.
Example:
text[-8, -2, -15]
Nothing exceeds:
text0
so algorithm incorrectly keeps:
24. Alternative extreme sentinel
Sometimes algorithms use conceptual values such as:
textmax = -infinity min = +infinity
Then every real input can update appropriately.
But for manual CT problems, using the first valid observation is often cleaner.
25. Finding max among filtered data
Suppose:
Find the largest even number.
Now two conditions are involved:
- value must be even
- among eligible values, find largest
Conceptually:
textfor each x: if x is even: compare x with current maximum
Filtering happens before max comparison.
26. Careful initialization with filters
Suppose:
textdata = [3, 8, 5, 12]
and we want maximum even value.
You cannot simply initialize:
textmax_even = first value
because first value:
text3
is not even.
Instead initialize from the first qualifying value, or maintain a flag indicating whether one has been found.
27. Flag pattern
Example:
textfound = False for each x: if x is even: if found == False: max_even = x found = True else if x > max_even: max_even = x
This handles cases where qualifying values may appear later.
28. Why this matters
What if data are:
text3, 5, 7
and you ask for maximum even value?
There is no valid answer from the dataset.
A proper algorithm should detect:
textfound = False
at the end.
29. AND operator
The logical
AND combines conditions.Expression:
textA AND B
is true only if:
- A is true
- B is true
30. AND truth table
| A | B | A AND B |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
So:
requires both.
31. Example
Condition:
textage >= 18 AND age <= 60
means age must satisfy:
Both boundaries must hold.
32. Range filtering with AND
Suppose we want numbers strictly between 10 and 20:
textx > 10 AND x < 20
This selects:
text11, 12, ..., 19
if integers are involved.
33. Example
For:
textx = 15
we have:
text15 > 10 → True 15 < 20 → True
Therefore:
textTrue AND True → True
34. Another example
For:
textx = 25
text25 > 10 → True 25 < 20 → False
Then:
textTrue AND False → False
So it is filtered out.
35. AND with multiple criteria
Example:
Count students who scored above 60 and attended at least 75%.
Condition:
textmarks > 60 AND attendance >= 75
Both must be satisfied.
36. Example table
| Student | Marks | Attendance | Selected? |
|---|---|---|---|
| A | 80 | 90 | Yes |
| B | 80 | 60 | No |
| C | 50 | 90 | No |
| D | 70 | 80 | Yes |
Only A and D satisfy both.
37. AND vs nested conditions
These are often equivalent:
textif A AND B: action
and:
textif A: if B: action
Both require A and B.
38. But structure can matter
Consider:
textif A: action1 if B: action2
Now:
action1requires only Aaction2requires A and B
So do not mechanically merge every nested condition.
39. Short-circuit intuition
In many programming systems:
textA AND B
may stop checking once A is false.
Why?
Because:
textFalse AND anything
must be false.
This is called short-circuit evaluation.
Useful conceptually, though exact pseudocode semantics depend on the course notation.
40. Combining filtering and AND
Suppose:
Sum values between 5 and 10 inclusive.
Pseudocode:
texttotal = 0 for each x: if x >= 5 AND x <= 10: total = total + x
41. Example
Data:
text3, 5, 7, 11, 10
Selected:
text5, 7, 10
Sum:
42. Finding maximum with AND
Suppose each record has:
- age
- salary
Question:
Find maximum salary among people aged 20–30.
Filter:
textage >= 20 AND age <= 30
Then among only those records:
textcompare salary with max
This is a common multi-stage CT pattern.
43. Selection can update different variables
Example:
textpositive = 0 negative = 0 for each x: if x > 0: positive = positive + 1 else: negative = negative + 1
One condition decides which state variable changes.
44. Partitioning data
A selection can divide a dataset into categories.
Example:
textif x < 0: negative else if x == 0: zero else: positive
Every number belongs to exactly one category.
45. Exhaustive selection
A set of conditions is exhaustive if every possible input matches some branch.
Example:
textif x > 0: ... else if x == 0: ... else: ...
covers every real number.
46. Mutually exclusive branches
Branches are mutually exclusive when an item cannot satisfy more than one selected branch in the same decision chain.
Example:
textif x < 0 else if x == 0 else
Only one branch executes.
47. Independent ifs vs if/else
Compare:
textif x > 0: A if x > 10: B
For:
both A and B happen.
But:
textif x > 0: A else if x > 10: B
For:
only A happens because first condition already matched.
This distinction is important.
48. Selection order trap
Consider:
textif marks >= 40: grade = "Pass" else if marks >= 90: grade = "Excellent"
For:
the first condition is already true.
So
"Excellent" is never reached.Correct ordering would put the more specific condition first.
49. Maximum and minimum together
You can compute both in one pass:
textmax = first value min = first value for each remaining x: if x > max: max = x if x < min: min = x
Time-wise, one traversal is enough.
50. Example
Data:
text7, 2, 10, 4
Start:
textmin = 7 max = 7
After full scan:
51. Range from min/max
Once min and max are known:
So CT algorithms can directly implement statistical summaries from Stats Week 3.
52. Counting max occurrences
Suppose we want:
maximum value and how often it occurs.
A useful pattern:
textmax = first value count = 1 for each remaining x: if x > max: max = x count = 1 else if x == max: count = count + 1
53. Why reset count?
Suppose current maximum is:
and it occurred three times.
Then we encounter:
All previous counts of 5 are irrelevant because 5 is no longer the maximum.
So:
textcount = 1
for the newly discovered maximum.
54. Example trace
Data:
text3, 5, 5, 2, 8, 8, 8
Progress:
textmax=3, count=1 max=5, count=1 max=5, count=2 max=5, count=2 max=8, count=1 max=8, count=2 max=8, count=3
Final:
Common mistake:
AND vs ORSuppose requirement is:
age is between 18 and 60.
Correct:
textage >= 18 AND age <= 60
Using OR:
textage >= 18 OR age <= 60
is true for almost every real age.
For example:
satisfies:
textage >= 18
so entire OR becomes true.
Common mistake: impossible AND
Condition:
textx < 5 AND x > 10
can never be true.
No number is simultaneously:
and:
Always inspect whether combined constraints are compatible.
Common mistake: using first data item despite filtering
If the task is:
maximum among positive values,
and first value is negative, initializing max to the first value can produce awkward logic.
Initialize using the first valid filtered item or use a flag.
Common mistake: resetting maximum inside loop
Wrong:
textfor each x: max = first_value if x > max: max = x
This repeatedly discards progress.
Initialization should usually happen once, before the loop.
Common mistake: update max in wrong direction
To find maximum:
textif x > max
not:
textif x < max
The second pattern finds minimum-like behavior.
Common mistake: output current item instead of state
Suppose the loop ends on:
textx = 6
while:
textmax = 11.
If asked for maximum, output:
textmax
not the iterator:
textx
Common mistake: confuse filtering with stopping
textif x < 0: ignore x
does not normally mean:
terminate the entire loop.
It means:
do not process this particular item further.
Filtering and termination are different.
Common mistake: infer values instead of tracing
If pseudocode says:
textA = A + 2
then A increases by 2.
Even if you think it "should" count items by 1, do not repair the algorithm while solving a tracing question.
63. Core pattern: counting with two conditions
textcount = 0 for each record: if condition1 AND condition2: count = count + 1
This pattern appears everywhere.
Example:
- female AND age > 50
- marks > 60 AND attendance > 75
- price < 1000 AND rating >= 4
64. Core pattern: maximum
textmax = first valid item for each remaining valid item x: if x > max: max = x
Remember:
65. Core pattern: minimum
textmin = first valid item for each remaining valid item x: if x < min: min = x
Remember:
66. Core pattern: classify
textfor each x: if condition A: category_A = category_A + 1 else: category_B = category_B + 1
This partitions data into groups.
67. Core pattern: range filter
textif lower <= x AND x <= upper: process x
Mathematically:
68. Trace example
Consider:
textA = 0 B = 0 for each x in [4, 9, 12, 3, 15]: if x > 5 AND x < 14: A = A + 1 B = B + x
Trace:
| x | x>5 | x<14 | AND | A | B |
|---|---|---|---|---|---|
| 4 | F | T | F | 0 | 0 |
| 9 | T | T | T | 1 | 9 |
| 12 | T | T | T | 2 | 21 |
| 3 | F | T | F | 2 | 21 |
| 15 | T | F | F | 2 | 21 |
Final:
69. Another trace: max
textM = 6 for each x in [2, 9, 5, 12, 10]: if x > M: M = x
Progress:
Final:
70. Week 1 → Week 2 connection
Week 1 gave:
- variables
- initialization
- basic iteration
- filtering
Week 2 adds:
- richer conditions
- selection
- explicit pseudocode reasoning
- max/min patterns
- Boolean conjunction
So the algorithm can now do more than simply traverse data.
It can make decisions and retain the most important observation seen so far.
71. Week 2 mental map
textDATA ↓ Iterate ↓ Check condition(s) ↓ Selection ├── ignore item ├── update count/sum ├── update maximum └── update minimum ↓ Continue ↓ Final state
72. What you should actually master
By the end of CT Week 2, you should be able to:
- Trace an iterative algorithm accurately.
- Explain filtering.
- Distinguish filtering from selection.
- Read and write simple pseudocode.
- Use
if/elselogic. - Understand why branch order matters.
- Find maximum in one pass.
- Find minimum in one pass.
- Initialize max/min safely.
- Find max/min among filtered items.
- Use the
ANDoperator correctly. - Evaluate combined Boolean conditions.
- Distinguish independent
ifs fromif/else. - Combine filtering with counting or summation.
- Build trace tables rather than relying on intuition.
If those are comfortable, Computational Thinking Week 2 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 2 Diagnostic: To find the maximum score in a dataset using a single pass, how should the accumulator variable
max_so_farbe initialized? :: Answer: A — To find a maximum, initializemax_so_farto the lowest possible value so any real element can replace it on first comparison. - Week 2 Diagnostic: If condition A is True and condition B is False, what does (A and B) evaluate to? :: Answer: B — The logical AND operator requires both operands to be True. If either is False, the result is False.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
To find the maximum score in a dataset using a single pass, how should the accumulator variable
max_so_far be initialized?MCQ
3 Unit Assessment
A. To 0 or -infinity (a value less than or equal to any valid score)
B. To the sum of all scores
C. To +infinity
D. To the length of the dataset
2
Question 2
If condition A is True and condition B is False, what does (A and B) evaluate to?
MCQ
3 Unit Assessment
A. True
B. False
C. None
D. Error