Registry Synced

Week 3: Multiple Iterations & Procedures

3282 words
16 min read
2026-09-12

Reading compass

Now · TL;DR

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:
text
one pass over data
Week 3 adds two major ideas:
  1. multiple separate passes
  2. reusable blocks of logic
The core structure becomes:
text
Pass 1 over data
↓
derive some state

Pass 2 over data
↓
derive something else

Procedure
↓
reuse logic with parameters
And logically:
text
A 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:
text
for 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

text
for each x:
    ...

for each y:
    ...
If each loop processes nn items, total work is roughly:
n+n=2n.n+n=2n.

Nested

text
for each x:
    for each y:
        ...
Now work may be roughly:
n2.n^2.
The structural difference is crucial.
Nested iteration becomes a formal Week 4 topic.

3. Example of two passes

Suppose the data are:
text
4, 8, 2, 10
We want:
  1. maximum
  2. count of values equal to maximum
One approach uses two passes.

4. Pass 1: find maximum

text
max = first value

for each remaining x:
    if x > max:
        max = x
For:
text
4, 8, 2, 10
final:
max=10\boxed{max=10}

5. Pass 2: count maximum

Now:
text
count = 0

for each x:
    if x == max:
        count = count + 1
If data were:
text
4, 10, 2, 10, 7
then:
count=2\boxed{count=2}

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:
Pass 1 derives context→Pass 2 uses context\boxed{ \text{Pass 1 derives context} \rightarrow \text{Pass 2 uses context} }

7. Example: above-average count

Suppose:
text
2, 4, 8, 10
We want number of values greater than the mean.
First we need:
mean.\text{mean}.
That itself requires processing all values.

8. First pass

text
sum = 0
count = 0

for each x:
    sum = sum + x
    count = count + 1
Then:
mean=sumcount.mean=\frac{sum}{count}.
For the data:
mean=244=6.mean=\frac{24}{4}=6.

9. Second pass

text
above = 0

for each x:
    if x > mean:
        above = above + 1
Values above 6:
text
8, 10
So:
above=2\boxed{above=2}

10. Multiple passes preserve earlier results

After pass 1, variables such as:
text
mean
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:
text
count
to count all items.
Second pass needs a new count:
text
above = 0
Do not accidentally overwrite:
text
mean
or other state needed later.

12. Loop independence

In non-nested loops:
text
for 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

text
A = 0

for each x in [1, 2]:
    A = A + x

for each y in [3, 4]:
    A = A + y
Execution:
First loop:
0→1→3.0\to1\to3.
Second loop:
3→6→10.3\to6\to10.
Final:
A=10\boxed{A=10}

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:
text
70, 85, 60, 95, 90
We want:
  • first prize → largest score
  • second prize → second largest
  • third prize → third largest
Expected ranking:
95, 90, 85.95,\ 90,\ 85.

16. State needed

Instead of one variable:
text
max
we need several:
text
first
second
third
with invariant:
first≥second≥thirdfirst\geq second\geq third
among the best values seen so far.

17. Update intuition

Suppose currently:
text
first  = 95
second = 85
third  = 70
and new score:
text
90
Then 90 belongs between first and second.
So state becomes:
text
first  = 95
second = 90
third  = 85
One value gets inserted and lower ranks shift.

18. General ranking logic

For a new value x:
text
if 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:
text
first = 100
second = 90
third = 80
New:
text
x = 110
You cannot immediately do:
text
first = 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:
text
third = second
second = first
first = x
With:
text
100, 90, 80
and:
text
x = 110
we get:
text
third = 90
second = 100
first = 110
Correct.

21. Multiple-pass alternative

Top-three values can also be found using multiple passes.
For example:
  1. find largest
  2. find largest value below the first
  3. 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:
text
procedure 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:
text
calculate sum of A
calculate sum of B
calculate sum of C
With procedure:
text
sum(A)
sum(B)
sum(C)
The same logic is reused.

25. Procedure invocation

If we define:
text
procedure showMessage:
    print "Done"
then calling:
text
showMessage()
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:
text
procedure square(x):
    return x * x
Here:
text
x
is a parameter.

27. Arguments

When we call:
text
square(5)
the value:
text
5
is the argument supplied to parameter:
text
x
So conceptually:
  • parameter = placeholder in definition
  • argument = actual value in invocation

28. Example

Procedure:
text
procedure bigger(a, b):
    if a > b:
        return a
    else:
        return b
Call:
text
bigger(10, 7)
Parameters receive:
text
a = 10
b = 7
Output:
10.10.

29. Multiple parameters

A procedure can have several parameters:
text
procedure insideRange(x, low, high):
    if x >= low AND x <= high:
        return True
    else:
        return False
Call:
text
insideRange(7, 5, 10)
returns:
text
True

30. Parameter values are local inputs conceptually

When a procedure is called, its parameters get values for that invocation.
Example:
text
square(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:
text
procedure add(a, b):
    return a + b
Call:
text
x = add(3, 4)
then:
text
x = 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

text
procedure double(x):
    return 2 * x
Calling:
text
double(5)
returns:
10.10.
Nothing else necessarily changes.

35. Example with side effect

Suppose:
text
count = 0

procedure increment:
    count = count + 1
Calling:
text
increment()
changes external variable:
text
count
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:
  1. what parameters does it receive?
  2. what value does it return?
  3. what external variables/data does it modify?

37. Example

text
A = 5

procedure change(x):
    A = A + x
Call:
text
change(3)
If A is externally accessible to the procedure, then:
A:5→8.A:5\to8.
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:
text
procedure f(x):
    return x*x + 1
Same input:
xx
gives same output and leaves external state untouched.
This is a useful conceptual contrast.

39. Procedures reduce duplication

Suppose an algorithm repeatedly checks:
text
x >= 0 AND x <= 100
You could create:
text
procedure validMark(x):
    ...
Then call:
text
validMark(mark)
This makes the algorithm easier to understand.

40. Procedure execution order

Consider:
text
A = 2

procedure f(x):
    return x + 3

A = f(A)
A = A * 2
Trace:
  1. A = 2
  2. call f(2)
  3. return 5
  4. assign A = 5
  5. multiply by 2
Final:
A=10\boxed{A=10}

41. OR operator

The logical OR operator is true if at least one input condition is true.
Notation conceptually:
text
A OR B
or mathematically:
A∨B.A\lor B.

42. OR truth table

ABA OR B
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue
So OR is false only when both conditions are false.

43. AND vs OR

AND

Both conditions must hold:
A∧B.A\land B.

OR

At least one must hold:
A∨B.A\lor B.
This distinction should become automatic.

44. Range-inside condition

To check whether:
10<x<20,10<x<20,
use:
text
x > 10 AND x < 20
because both inequalities must hold.

45. Outside-range condition

To check whether xx is outside:
[10,20],[10,20],
use:
text
x < 10 OR x > 20
because either side is enough.

46. Example

For:
x=5,x=5,
condition:
text
x < 10 OR x > 20
becomes:
text
True OR False
which is:
text
True
So 5 is outside the range.

47. Another example

For:
x=15,x=15,
we get:
text
False OR False
thus:
text
False
So 15 is not outside the interval.

48. OR in categorical conditions

Suppose eligible department is:
text
"CS" OR "Math"
Conceptually:
text
if department == "CS" OR department == "Math":
    eligible
Either category qualifies.

49. OR for multiple special cases

Example:
flag temperature if below 0 or above 50.
text
if temperature < 0 OR temperature > 50:
    flag
Either extreme triggers the action.

50. Inclusive OR

In standard logical OR:
text
True OR True
is still:
text
True
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:
NOT(A AND B)=(NOT A) OR (NOT B)\boxed{ \text{NOT}(A\text{ AND }B) = (\text{NOT }A)\text{ OR }(\text{NOT }B) }
and:
NOT(A OR B)=(NOT A) AND (NOT B)\boxed{ \text{NOT}(A\text{ OR }B) = (\text{NOT }A)\text{ AND }(\text{NOT }B) }
These mirror the set-theory De Morgan laws from Maths and probability.

53. Example

Condition:
text
NOT(x >= 10 AND x <= 20)
means:
x is not inside [10,20].
Equivalent to:
text
x < 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":
text
x >= 10 OR x <= 20
Almost every number satisfies at least one side.
Correct:
text
x >= 10 AND x <= 20

Common mistake: AND instead of OR outside interval
Wrong:
text
x < 10 AND x > 20
Impossible.
Correct:
text
x < 10 OR x > 20

Common mistake: assuming multiple loops are nested
Given:
text
for each x:
    ...

for each y:
    ...
do not multiply iteration counts automatically.
They are sequential loops.

Common mistake: reset shared state unintentionally
Example:
text
max = ...

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:
text
procedure f():
    count = count + 1
If you call:
text
f()
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:
text
x = 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:
text
first = 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:
text
first
second
third
store the three highest eligible scores seen so far, in descending order.
So throughout execution:
first≥second≥third\boxed{ first\geq second\geq third }
subject to the chosen tie policy.

62. Tie handling

Suppose scores:
text
100, 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:
text
A = 1

procedure p(x):
    A = A + x
    return A

B = p(3)
C = p(2)
Assuming A is externally modified:
First call:
A=1+3=4A=1+3=4
and:
B=4.B=4.
Second call:
A=4+2=6A=4+2=6
and:
C=6.C=6.
Final:
A=6, B=4, C=6\boxed{ A=6,\ B=4,\ C=6 }
This is a classic side-effect style trace.

64. Multiple-pass trace example

text
M = 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:
M=12.M=12.
Then:
M/3=4.M/3=4.
Second pass counts values:
>4.>4.
Only:
66
qualifies.
Thus:
C=1\boxed{C=1}

65. Procedure mental model

text
Procedure definition
      ↓
parameters specify inputs
      ↓
body executes
      ↓
may return value
      ↓
may cause side effects
      ↓
execution resumes after call

66. Week 3 master map

text
MULTIPLE 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:
one pass + decisions\text{one pass + decisions}
Week 3:
multiple passes + reusable procedures\text{multiple passes + reusable procedures}
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:
  1. Distinguish multiple non-nested loops from nested loops.
  2. Trace sequential loops correctly.
  3. Understand why multiple passes are sometimes necessary.
  4. Preserve state from one pass for use in another.
  5. Understand the top-three / Three Prizes pattern.
  6. Track multiple best values safely.
  7. Explain what a procedure is.
  8. Identify procedure parameters.
  9. Distinguish parameters from arguments.
  10. Trace procedure calls.
  11. Understand return values.
  12. Recognize side effects.
  13. Track external state modified by a procedure.
  14. Evaluate OR conditions.
  15. Distinguish AND from OR.
  16. Use AND for inside-range conditions.
  17. Use OR for 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
Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.