Week 3: Multiple Iterations & Procedures
3282 words
16 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
Sequential non-nested iterations, the Three Prizes problem, reusable procedures, parameters, side effects, and OR operator. # Computational Thinking — Week 3: Multiple Iterations & Procedures IITM’s CT Week 3 covers **multiple iterations (non-nested), the Three Prizes problem, procedures, parameters, side effects, a...

Computational Thinking — Week 3: Multiple Iterations & Procedures
IITM’s CT Week 3 covers multiple iterations (non-nested), the Three Prizes problem, procedures, parameters, side effects, and the OR operator.
TL;DR
Week 2 was mostly:
textone pass over data
Week 3 adds two major ideas:
- multiple separate passes
- reusable blocks of logic
The core structure becomes:
textPass 1 over data ↓ derive some state Pass 2 over data ↓ derive something else Procedure ↓ reuse logic with parameters
And logically:
textA OR B
is true if at least one condition is true.
1. Multiple non-nested iterations
A non-nested multiple-iteration algorithm contains more than one loop, but the loops occur one after another, not inside one another.
Example:
textfor each x in data: do task A for each x in data: do task B
The second loop starts only after the first has completely finished.
2. Non-nested vs nested
Non-nested
textfor each x: ... for each y: ...
If each loop processes n items, total work is roughly:
Nested
textfor each x: for each y: ...
Now work may be roughly:
The structural difference is crucial.
Nested iteration becomes a formal Week 4 topic.
3. Example of two passes
Suppose the data are:
text4, 8, 2, 10
We want:
- maximum
- count of values equal to maximum
One approach uses two passes.
4. Pass 1: find maximum
textmax = first value for each remaining x: if x > max: max = x
For:
text4, 8, 2, 10
final:
5. Pass 2: count maximum
Now:
textcount = 0 for each x: if x == max: count = count + 1
If data were:
text4, 10, 2, 10, 7
then:
6. Why use multiple passes?
Sometimes a later computation needs information that can only be known after scanning the whole dataset.
Examples:
- find mean, then count values above mean
- find maximum, then locate all maxima
- find minimum, then compare all values to it
- compute threshold in first pass, classify in second
So:
7. Example: above-average count
Suppose:
text2, 4, 8, 10
We want number of values greater than the mean.
First we need:
That itself requires processing all values.
8. First pass
textsum = 0 count = 0 for each x: sum = sum + x count = count + 1
Then:
For the data:
9. Second pass
textabove = 0 for each x: if x > mean: above = above + 1
Values above 6:
text8, 10
So:
10. Multiple passes preserve earlier results
After pass 1, variables such as:
textmean max min
may be retained.
Then pass 2 can use them.
This is an important state-flow idea.
11. Reset only what must be reset
Suppose first pass uses:
textcount
to count all items.
Second pass needs a new count:
textabove = 0
Do not accidentally overwrite:
textmean
or other state needed later.
12. Loop independence
In non-nested loops:
textfor each x: ... for each y: ...
the second loop does not execute once per
x.It executes only after the first loop finishes.
This is a common tracing mistake.
13. Trace-order example
textA = 0 for each x in [1, 2]: A = A + x for each y in [3, 4]: A = A + y
Execution:
First loop:
Second loop:
Final:
14. Three Prizes problem
The syllabus explicitly includes the Three Prizes problem.
The key computational idea is typically maintaining several best candidates rather than only one maximum.
Conceptually:
track first, second and third best values.
15. Simplified top-three idea
Suppose scores are:
text70, 85, 60, 95, 90
We want:
- first prize → largest score
- second prize → second largest
- third prize → third largest
Expected ranking:
16. State needed
Instead of one variable:
textmax
we need several:
textfirst second third
with invariant:
among the best values seen so far.
17. Update intuition
Suppose currently:
textfirst = 95 second = 85 third = 70
and new score:
text90
Then 90 belongs between first and second.
So state becomes:
textfirst = 95 second = 90 third = 85
One value gets inserted and lower ranks shift.
18. General ranking logic
For a new value
x:textif x > first: third = second second = first first = x else if x > second: third = second second = x else if x > third: third = x
This assumes appropriate initialization and a chosen policy for ties.
19. Why order of updates matters
Suppose:
textfirst = 100 second = 90 third = 80
New:
textx = 110
You cannot immediately do:
textfirst = 110 second = first
because now
first already contains 110.You would lose the old 100.
Correct logical sequence preserves old values before overwriting.
20. Correct shifting
Conceptually:
textthird = second second = first first = x
With:
text100, 90, 80
and:
textx = 110
we get:
textthird = 90 second = 100 first = 110
Correct.
21. Multiple-pass alternative
Top-three values can also be found using multiple passes.
For example:
- find largest
- find largest value below the first
- find largest below the second
This is conceptually simpler, though it may scan the data multiple times.
That connects directly to the week's multiple-iteration theme.
22. Procedure
A procedure is a named block of instructions that performs some task.
Example:
textprocedure greet: print "Hello"
Instead of rewriting the same instructions repeatedly, we invoke the procedure.
23. Why procedures matter
Procedures help with:
- reuse
- abstraction
- readability
- modularity
- reducing duplication
Instead of thinking about every low-level step repeatedly, we package a task behind a name.
24. Example
Without procedure:
textcalculate sum of A calculate sum of B calculate sum of C
With procedure:
textsum(A) sum(B) sum(C)
The same logic is reused.
25. Procedure invocation
If we define:
textprocedure showMessage: print "Done"
then calling:
textshowMessage()
executes the procedure body.
Execution then returns to the statement after the call.
26. Parameter
A parameter is an input accepted by a procedure.
Example:
textprocedure square(x): return x * x
Here:
textx
is a parameter.
27. Arguments
When we call:
textsquare(5)
the value:
text5
is the argument supplied to parameter:
textx
So conceptually:
- parameter = placeholder in definition
- argument = actual value in invocation
28. Example
Procedure:
textprocedure bigger(a, b): if a > b: return a else: return b
Call:
textbigger(10, 7)
Parameters receive:
texta = 10 b = 7
Output:
29. Multiple parameters
A procedure can have several parameters:
textprocedure insideRange(x, low, high): if x >= low AND x <= high: return True else: return False
Call:
textinsideRange(7, 5, 10)
returns:
textTrue
30. Parameter values are local inputs conceptually
When a procedure is called, its parameters get values for that invocation.
Example:
textsquare(3) square(7)
The same procedure works with different arguments.
This is the core benefit of parameterization.
31. Return value
Some procedures compute and produce a result.
Example:
textprocedure add(a, b): return a + b
Call:
textx = add(3, 4)
then:
textx = 7
32. Procedure vs return
A procedure may:
- return a value
- change some external state
- print output
- perform multiple actions
These are conceptually different effects.
33. Side effect
A side effect occurs when a procedure changes something outside its local computation.
Examples:
- changing a global variable
- modifying a shared table
- printing
- writing to a file
- updating an external object
In CT, the main idea is:
calling the procedure may change state beyond merely producing a returned value.
34. Example without side effect
textprocedure double(x): return 2 * x
Calling:
textdouble(5)
returns:
Nothing else necessarily changes.
35. Example with side effect
Suppose:
textcount = 0 procedure increment: count = count + 1
Calling:
textincrement()
changes external variable:
textcount
That is a side effect.
36. Why side effects matter
Side effects make tracing harder because a procedure call may alter state elsewhere.
When you see a procedure call, ask:
- what parameters does it receive?
- what value does it return?
- what external variables/data does it modify?
37. Example
textA = 5 procedure change(x): A = A + x
Call:
textchange(3)
If
A is externally accessible to the procedure, then:The call has a side effect.
38. Pure-function intuition
A procedure with no side effects and whose output depends only on inputs behaves like a mathematical function.
Example:
textprocedure f(x): return x*x + 1
Same input:
gives same output and leaves external state untouched.
This is a useful conceptual contrast.
39. Procedures reduce duplication
Suppose an algorithm repeatedly checks:
textx >= 0 AND x <= 100
You could create:
textprocedure validMark(x): ...
Then call:
textvalidMark(mark)
This makes the algorithm easier to understand.
40. Procedure execution order
Consider:
textA = 2 procedure f(x): return x + 3 A = f(A) A = A * 2
Trace:
A = 2- call
f(2) - return
5 - assign
A = 5 - multiply by 2
Final:
41. OR operator
The logical
OR operator is true if at least one input condition is true.Notation conceptually:
textA OR B
or mathematically:
42. OR truth table
| A | B | A OR B |
|---|---|---|
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |
So OR is false only when both conditions are false.
43. AND vs OR
AND
Both conditions must hold:
OR
At least one must hold:
This distinction should become automatic.
44. Range-inside condition
To check whether:
use:
textx > 10 AND x < 20
because both inequalities must hold.
45. Outside-range condition
To check whether x is outside:
use:
textx < 10 OR x > 20
because either side is enough.
46. Example
For:
condition:
textx < 10 OR x > 20
becomes:
textTrue OR False
which is:
textTrue
So 5 is outside the range.
47. Another example
For:
we get:
textFalse OR False
thus:
textFalse
So 15 is not outside the interval.
48. OR in categorical conditions
Suppose eligible department is:
text"CS" OR "Math"
Conceptually:
textif department == "CS" OR department == "Math": eligible
Either category qualifies.
49. OR for multiple special cases
Example:
flag temperature if below 0 or above 50.
textif temperature < 0 OR temperature > 50: flag
Either extreme triggers the action.
50. Inclusive OR
In standard logical OR:
textTrue OR True
is still:
textTrue
So OR means:
one or the other or both.
This is the same inclusive-OR idea you saw in probability unions.
51. Exclusive OR intuition
Sometimes ordinary language says:
either A or B, but not both.
That is exclusive OR, which differs from standard OR.
Standard Week 3 OR should generally be understood as inclusive unless the problem explicitly says otherwise.
52. De Morgan intuition
Useful logical relationships:
and:
These mirror the set-theory De Morgan laws from Maths and probability.
53. Example
Condition:
textNOT(x >= 10 AND x <= 20)
means:
x is not inside [10,20].
Equivalent to:
textx < 10 OR x > 20
This is useful when simplifying conditions.
Common mistake: OR instead of AND for bounded interval
Wrong for "between 10 and 20":
textx >= 10 OR x <= 20
Almost every number satisfies at least one side.
Correct:
textx >= 10 AND x <= 20
Common mistake: AND instead of OR outside interval
Wrong:
textx < 10 AND x > 20
Impossible.
Correct:
textx < 10 OR x > 20
Common mistake: assuming multiple loops are nested
Given:
textfor each x: ... for each y: ...
do not multiply iteration counts automatically.
They are sequential loops.
Common mistake: reset shared state unintentionally
Example:
textmax = ... for each x: ... max = 0 for each x: ...
If the second pass needs the first-pass maximum, resetting it destroys required information.
Trace assignments carefully.
Common mistake: procedure call has hidden effects
Suppose:
textprocedure f(): count = count + 1
If you call:
textf() f() f()
external
count may change three times.Do not treat the procedure as merely a label.
Common mistake: confuse parameter and external variable
Suppose:
textx = 10 procedure f(x): x = x + 1
There may be a distinction between:
- outer
x - parameter
x
The exact scope rules depend on the pseudocode convention, so trace according to the course's semantics rather than assuming every same-name variable is identical.
Common mistake: overwrite before shifting
For top-three tracking:
textfirst = x second = first
loses the previous
first.When values must shift, preserve old state in the correct order.
61. Three-prizes invariant
A strong mental model is:
After processing each score:
textfirst second third
store the three highest eligible scores seen so far, in descending order.
So throughout execution:
subject to the chosen tie policy.
62. Tie handling
Suppose scores:
text100, 100, 90
Does this mean:
- first = 100
- second = 100
- third = 90
or should prizes go to distinct score values?
The answer depends on the problem statement.
Do not invent a tie policy.
63. Procedure trace example
Consider:
textA = 1 procedure p(x): A = A + x return A B = p(3) C = p(2)
Assuming
A is externally modified:First call:
and:
Second call:
and:
Final:
This is a classic side-effect style trace.
64. Multiple-pass trace example
textM = 0 for each x in [2, 6, 4]: M = M + x C = 0 for each x in [2, 6, 4]: if x > M / 3: C = C + 1
First pass:
Then:
Second pass counts values:
Only:
qualifies.
Thus:
65. Procedure mental model
textProcedure definition ↓ parameters specify inputs ↓ body executes ↓ may return value ↓ may cause side effects ↓ execution resumes after call
66. Week 3 master map
textMULTIPLE ITERATIONS ├── Pass 1: derive context └── Pass 2: use context THREE PRIZES └── maintain multiple best values PROCEDURES ├── reusable logic ├── parameters ├── return values └── side effects BOOLEAN LOGIC ├── AND → all conditions └── OR → at least one condition
67. Week 2 → Week 3 connection
Week 2:
Week 3:
So your algorithms are becoming modular and capable of retaining more complex state.
68. What you should actually master
By the end of CT Week 3, you should be able to:
- Distinguish multiple non-nested loops from nested loops.
- Trace sequential loops correctly.
- Understand why multiple passes are sometimes necessary.
- Preserve state from one pass for use in another.
- Understand the top-three / Three Prizes pattern.
- Track multiple best values safely.
- Explain what a procedure is.
- Identify procedure parameters.
- Distinguish parameters from arguments.
- Trace procedure calls.
- Understand return values.
- Recognize side effects.
- Track external state modified by a procedure.
- Evaluate
ORconditions. - Distinguish
ANDfromOR. - Use
ANDfor inside-range conditions. - Use
ORfor outside-range or alternative conditions.
If these are comfortable, Computational Thinking Week 3 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 3 Diagnostic: What is the primary difference between a pure procedure and a procedure with side effects? :: Answer: B — A side effect occurs when a procedure modifies external state, writes to a file, or updates a global structure beyond returning a local value.
- Week 3 Diagnostic: If condition A is True and condition B is False, what does (A or B) evaluate to? :: Answer: A — The logical OR operator evaluates to True if at least one operand is True.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
What is the primary difference between a pure procedure and a procedure with side effects?
MCQ
3 Unit Assessment
A. Pure procedures execute faster than side-effecting ones
B. A procedure with side effects modifies state or produces output outside its local scope
C. Pure procedures do not accept parameters
D. Side-effecting procedures cannot return values
2
Question 2
If condition A is True and condition B is False, what does (A or B) evaluate to?
MCQ
3 Unit Assessment
A. True
B. False
C. None
D. Error