Quiz 2

Week 3: Procedures & Parameters

2414 words
12 min read
Python Week 1: the first filter for runtime behavior
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 3: Procedures & Parameters > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Week 2 (Pseudocode, Iteration) **Cross-links:** BSCS1002-Python (Week 4 — Functions), BSCS2002-PDSA (Week 3 — Modularity) ## 1. Motivation: Why Procedures?

Week 3: Procedures & Parameters

BSCS1001 — IIT Madras BS Degree Prerequisite: Week 2 (Pseudocode, Iteration) Cross-links: BSCS1002-Python (Week 4 — Functions), BSCS2002-PDSA (Week 3 — Modularity)

1. Motivation: Why Procedures?

Imagine you need to compute the maximum mark in Maths, Physics, Chemistry, and Total. Without procedures, you'd write:
sql
// Max Maths
MaxMaths = 0
while (Pile 1 has more cards) { Pick X; if X.Maths > MaxMaths → update }
// Max Physics (copy-paste, change field name)
MaxPhysics = 0
while (Pile 1 has more cards) { Pick X; if X.Physics > MaxPhysics → update }
// Max Chemistry (copy-paste again)
MaxChemistry = 0
while (Pile 1 has more cards) { Pick X; if X.Chemistry > MaxChemistry → update }
This is terrible:
  • 4 times the code
  • If you find a bug, you must fix it in 4 places
  • If you want to improve the algorithm, you change it 4 times
  • Boring to write, boring to read Procedures solve this: write the logic once, use it anywhere.
Real-world analogy: A procedure is like a power drill. You buy one drill (write one procedure) and attach different bits (pass different parameters) for different tasks.

2. What is a Procedure?

A procedure is a named block of pseudocode that performs a specific task. It can be called (used) from anywhere in your code. (Diagram)

Benefits of Procedures

BenefitExplanation
ReusabilityWrite once, use many times
ModularityBreak complex problems into smaller pieces
ReadabilityProcedure name describes what it does
MaintainabilityFix one place, all callers benefit
AbstractionCaller doesn't need to know how it works

3. Procedure Syntax

Defining a Procedure

pseudo
Procedure ProcedureName(parameter1, parameter2, ...) {
    // Body of the procedure
    // Statements using parameters
    return(value)
End ProcedureName

Example: Sum of Maths Marks for a Gender

sql
Procedure SumMaths(gen) {
    Sum = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        if (X.Gender == gen) {
            Sum = Sum + X.Maths
        }
    }
    return(Sum)
End SumMaths

Breaking Down the Syntax

PartExamplePurpose
Procedure keywordProcedureMarks the start
NameSumMathsIdentifies the procedure
Parameters(gen)Inputs the procedure needs
Body{ ... }The algorithm steps
returnreturn(Sum)Sends result back to caller
EndEnd SumMathsMarks the end

4. Parameters: Making Procedures Flexible

A parameter is a variable that receives a value when the procedure is called. It lets the same procedure work on different data.

How Parameters Work

(Diagram)

Example: Parameter as Field Name

We can even pass a field name as a parameter!
sql
Procedure SumMarks(gen, fld) {
    Sum = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        if (X.Gender == gen) {
            Sum = Sum + X.fld    // fld determines which field!
        }
    }
    return(Sum)
End SumMarks

Calls to This Procedure

CallMeaningReturns
SumMarks(F, Chemistry)Sum of girls' Chemistry marksChemistry total for girls
SumMarks(M, Physics)Sum of boys' Physics marksPhysics total for boys
SumMarks(F, Total)Sum of girls' total marksGrand total for girls

Multiple Parameters

Procedures can have any number of parameters:
sql
// Finding maximum in any subject for any gender
Procedure MaxMarks(gen, subject) {
    MaxVal = 0
    MaxId = -1
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        if (X.Gender == gen AND X.subject > MaxVal) {
            MaxVal = X.subject
            MaxId = X.Id
        }
    }
    return(MaxId, MaxVal)     // Return multiple values
End MaxMarks

5. Calling Procedures

Procedure Call as Expression

When a procedure returns a value, the call can be used in an expression:
python
GirlChemSum = SumMarks(F, Chemistry)
BoyChemSum = SumMarks(M, Chemistry)
if (GirlChemSum > BoyChemSum) {
    print("Congratulate the girls!")
}
else {
    print("Congratulate the boys!")
}

Procedure Call as Statement

When a procedure does not return a useful value, call it as a standalone statement:
sql
Procedure UpdateMarks(cardId, subject, newMarks) {
    // Find card with matching Id and update the marks
    // No return value needed
End UpdateMarks
// Call it:
UpdateMarks(17, Physics, 88)

How Arguments Match Parameters

When you call a procedure, the arguments you pass are assigned to the parameters in order:
pseudo
Procedure Example(a, b, c) {
    // a gets first argument, b gets second, c gets third
}
Call:   Example(10, 20, 30)
               ↑    ↑    ↑
               a ← 10, b ← 20, c ← 30

Complete Example: Top Student Analysis

sql
Procedure MaxMarks(fld) {
    MaxVal = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        if (X.fld > MaxVal) {
            MaxVal = X.fld
        }
    }
    return(MaxVal)
End MaxMarks
// Now use it:
MaxMaths = MaxMarks(Maths)
MaxPhysics = MaxMarks(Physics)
MaxChem = MaxMarks(Chemistry)
MaxTotal = MaxMarks(Total)
SubjTotal = MaxMaths + MaxPhysics + MaxChem
if (MaxTotal == SubjTotal) {
    SingleTopper = True
}
else {
    SingleTopper = False
}

6. Return Values

Procedures That Return a Value

pseudo
Procedure SumList(L) {
    total = 0
    foreach x in L {
        total = total + x
    }
    return(total)
End SumList
result = SumList([10, 20, 30])   // result = 60

Procedures That Don't Return a Value

Some procedures just do something rather than compute something:
python
Procedure PrintAll(L) {
    foreach x in L {
        print(x)
    }
End PrintAll
PrintAll([10, 20, 30])   // Prints 10, 20, 30 (no return value)

The return Statement

AspectBehavior
What it doesImmediately exits the procedure and sends the value back
Multiple returnsA procedure can have multiple return statements (different paths)
One valueEach return sends one value back (or multiple in some notations)
No returnIf no return, the procedure ends at End

7. The Three Prizes Problem

This is a classic problem from the course that shows the power of procedures.

Problem Statement

We need to find the top 3 students who are in the top 3 of at least one subject (Maths, Physics, Chemistry). Additionally, we need at least one boy and one girl among the winners.

Solution Approach

(Diagram)

Procedure: TopThreeMarks

pseudo
Procedure TopThreeMarks(Subj) {
    max = 0
    secondmax = 0
    thirdmax = 0
    while (Table 1 has more rows) {
        Read the first row X in Table 1
        if (X.Subj > max) {
            thirdmax = secondmax
            secondmax = max
            max = X.Subj
        }
        if (max > X.Subj AND X.Subj > secondmax) {
            thirdmax = secondmax
            secondmax = X.Subj
        }
        if (secondmax > X.Subj AND X.Subj > thirdmax) {
            thirdmax = X.Subj
        }
        Move X to Table 2
    }
    return(thirdmax)
End TopThreeMarks
Tracing TopThreeMarks for Maths [45, 78, 92, 61, 85]:
IterX.SubjmaxsecmaxthirdmaxAction
1454500X > max
27878450X > max (old max→second)
392927845X > max (shift all)
461927845No change
585928578X > secondmax (shift)
Third highest mark in Maths = 78

Building Lists of Top Students

pseudo
cutoffMaths = TopThreeMarks(Maths)
cutoffPhys = TopThreeMarks(Physics)
cutoffChem = TopThreeMarks(Chemistry)
mathsList = []
physList = []
chemList = []
while (Table 1 has more rows) {
    Read the first row X in Table 1
    if (X.Mathematics >= cutoffMaths) {
        mathsList = mathsList ++ [X.SeqNo]
    }
    if (X.Physics >= cutoffPhys) {
        physList = physList ++ [X.SeqNo]
    }
    if (X.Chemistry >= cutoffChem) {
        chemList = chemList ++ [X.SeqNo]
    }
    Move X to Table 2
}

Finding Students in All Three Lists

pseudo
// Students in both Maths and Physics top-3
mathsPhysList = []
foreach x in mathsList {
    foreach y in physList {
        if (x == y) {
            mathsPhysList = mathsPhysList ++ [x]
        }
    }
}
// Students in (Maths+Physics) AND Chemistry top-3
mathsPhysChemList = []
foreach x in mathsPhysList {
    foreach y in chemList {
        if (x == y) {
            mathsPhysChemList = mathsPhysChemList ++ [x]
        }
    }
}

8. Procedures vs Plain Code

Comparison Table

AspectPlain Code (No Procedures)With Procedures
Repeated logicCopy-paste everywhereWritten once
Code lengthLongCompact
Bug fixingFix in N placesFix in 1 place
ReadabilityHard to see forest for treesNamed operations are clear
TestingTest entire programTest each procedure separately
ReusabilityNoneCan reuse across programs
ModularityEverything is one big blockEach piece has clear responsibility

When NOT to Use a Procedure

  • For very simple operations (a single line)
  • When the operation is used only once (sometimes)
  • When the overhead of calling is not justified

9. Practice Questions

Basic Questions

Q1. What is a procedure? List two benefits.
Show Answer
A procedure is a named block of pseudocode that performs a specific task.
Benefits (any two):
  1. Reusability — write once, use many times
  2. Modularity — break complex problems into smaller pieces
  3. Readability — procedure name describes what it does
  4. Maintainability — fix one place, all callers benefit Q2. What is the difference between a parameter and an argument? Show Answer
  • Parameter: The variable listed in the procedure definition (e.g., gen in Procedure SumMaths(gen))
  • Argument: The actual value passed when calling (e.g., "F" in SumMaths(F))
The parameter receives the argument's value. Q3. Write a procedure called AverageMarks that takes a field name and returns the average of that field. Show Answer
sql
Procedure AverageMarks(fld) {
    Sum = 0
    Count = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        Sum = Sum + X.fld
        Count = Count + 1
    }
    return(Sum / Count)
End AverageMarks
Q4. What does SumMarks(F, Chemistry) return if there are no girls in the dataset?
Show Answer
It returns 0 because Sum starts at 0 and the condition X.Gender == "F" never matches, so Sum stays 0.

Intermediate Questions

Q5. Trace this procedure call for list [2, 5, 1, 8]:
pseudo
Procedure Mystery(L) {
    result = 0
    foreach x in L {
        if (x > result) {
            result = x
        }
    }
    return(result)
End Mystery
Call: answer = Mystery([2, 5, 1, 8])
Show Answer
IterxConditionresult
Init0
122>0 ✅2
255>2 ✅5
311>5 ❌5
488>5 ✅8
answer = 8 (the procedure finds maximum) Q6. Write a procedure CountAboveThreshold that takes a field name and a threshold value, and counts how many students exceed that threshold in that field. Show Answer
sql
Procedure CountAboveThreshold(fld, threshold) {
    Count = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        if (X.fld > threshold) {
            Count = Count + 1
        }
    }
    return(Count)
End CountAboveThreshold

// Example: CountAboveThreshold(Maths, 80)
Q7. Explain how Procedure MaxMarks(fld) works when called with different field names. How does X.fld access different fields?
Show Answer
When MaxMarks(Maths) is called, the parameter fld gets the value "Maths". Inside the loop, X.fld is interpreted as X.Maths — accessing the Maths field of card X.
When MaxMarks(Physics) is called, fld = "Physics", and X.fld accesses X.Physics.
This is a form of dynamic field access — the field name is treated as data. Q8. What would happen if we called SumMarks(M, Physics) but our procedure SumMarks only had one parameter? Show Answer
This would cause an error because the procedure expects 2 arguments but only received 1. The number of arguments must match the number of parameters.

Advanced Questions

Q9. Write a procedure IsSubjectTopper that takes a card X and the cutoff marks for Maths, Physics, and Chemistry, and returns True if X is in the top 3 of any subject.
Show Answer
pseudo
Procedure IsSubjectTopper(X, math3, phys3, chem3) {
    if (X.Mathematics >= math3) {
        return(True)
    }
    if (X.Physics >= phys3) {
        return(True)
    }
    if (X.Chemistry >= chem3) {
        return(True)
    }
    return(False)
End IsSubjectTopper
This procedure is used in the Three Prizes problem to check if a student qualifies. Q10. Design a procedure GradeAllocator that assigns grades A, B, C, D based on marks thresholds. Thresholds are passed as parameters. Show Answer
pseudo
Procedure GradeAllocator(marks, aThreshold, bThreshold, cThreshold) {
    if (marks >= aThreshold) {
        return("A")
    }
    if (marks >= bThreshold) {
        return("B")
    }
    if (marks >= cThreshold) {
        return("C")
    }
    return("D")
End GradeAllocator

// Usage:
// GradeAllocator(85, 90, 75, 60) returns "B"
Q11. Can a procedure call another procedure? Give an example.
Show Answer
Yes! This is called composition.
sql
Procedure Average(fld) {
    Sum = 0
    Count = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        Move X to Pile 2
        Sum = Sum + X.fld
        Count = Count + 1
    }
    return(Sum / Count)
End Average

Procedure CompareBoysGirls(subject) {
    boyAvg = Average(M, subject)    // Calling Average with gender filter?
    girlAvg = Average(F, subject)
    // (Note: Would need to modify Average to accept gender parameter)
}
Actually, to really compose, we'd need Average to accept a gender parameter too. Q12. In the Three Prizes problem, why do we compute the 3rd highest mark (not the 1st or 2nd) as the cutoff? Show Answer
If we used the 1st highest mark as the cutoff, only the single top student in each subject would qualify. But we want top 3 students per subject.
The 3rd highest mark tells us: "anyone at or above this mark is in the top 3." Students with marks equal to the 3rd highest are included, which gives us at least 3 students (possibly more if there are ties).
Using the 3rd highest mark as the cutoff ensures we capture all students who belong in the top 3 (including those who tied for 3rd place).

📚 Cross-References

CourseTopicConnection
BSCS1002 (Python)Week 4 — FunctionsPython def keyword, parameters, return
BSCS2002 (PDSA)Week 3 — ModularityDecomposition principles
BSCS2002 (PDSA)Week 6 — SortingUsing procedures for comparisons

Quiz Tip: Procedure questions often ask you to trace the return value or identify parameter-argument matching errors! Join Discord PreviousIteration & FilteringNextSide Effects of Procedures
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.