Weeks
Computational ThinkingWeek 3 · Tables, Procedures and Side Effects
Week 3 Notes

Computational
Thinking 3

Tables for data, procedures and parameters, the three prizes problem, and side effects. Lectures 3.1 to 3.9.

6 chapters33 worked examples~38 min read
TablesProceduresParametersSide effects

Chapters

  1. 01Presentation of Datasets as TablesLecture 3.1
  2. 02Pseudocode for Procedures and Parameters, Part 1Lecture 3.6
  3. 03Pseudocode for Procedures and Parameters, Part 2Lecture 3.7
  4. 04Pseudocode for the Three Prizes ProblemLecture 3.8
  5. 05Side Effects of ProceduresLecture 3.9
  6. 06Week 3 Summary SheetAll lectures
01
Lecture 3.1

Presentation of Datasets as Tables

Cards as rows of a table, and why a bill with a variable number of items must be split into linked tables.

Data usually arrives on cards: a grade card, a card for a word, a shopping bill. This lecture shows how to lay such data out as a table, and what goes wrong when a card has a variable amount of information, like a bill with any number of items.

1.1Extracting data from cards

  • Each card is a unit of information.
  • A card has different attributes (also called fields): Card ID, Name, Gender, ..., Total.
  • Organise the cards as a table: each attribute is a column and each card is a row.
  • All the grade cards go together in a single table.
ONE GRADE CARDALL CARDS, ONE TABLENameKavyaGenderFDoB12 JanCityChennaiMath64Phys72Chem68TOTAL204Id102417NameKavyaSiddharthArshadGenFMMCityChennaiMaduraiChennaiMath644462Phys727281Chem685867Total204174210this row = the card of Kavyaeach attribute is a columneach card is a row; every card has a value for every column
Figure 1. The grade card of Kavya (Id 10) becomes the first row of the table
IdNameGenDoBCityMathPhysChemTotal
10KavyaF12 JanChennai647268204
24SiddharthM26 DecMadurai447258174
17ArshadM14 DecChennai628167210
Remember

The column headings are the attribute names. A card never has a "missing column": every card in the table has a value for every attribute, so the table stays neat.

1.2The same idea for words

Cards can hold anything that has attributes. For the words in a paragraph, each word is a card with an Id, the Word itself, its Type (noun, verb, ...) and its Length.

IdWordTypeLength
24SaturdayNoun8
12consideredVerb10

1.3Shopping bills: a table that is no longer neat

Once per billBill-level attributes: Bill ID, Shop Name, Customer Name. The bill Total also belongs here.
Once per itemItem-level attributes: Item, Category, Qty, Price, Cost. A bill has a variable number of rows of these.
  • Variable number of columns? A card cannot have a different number of columns. The table is no longer neat.
  • Variable number of rows per card? Give a row to each item and tag the rows with the card (bill) Id.

Doing that gives one big table for the bill:

IdShopCustomerItemCategoryQtyPriceCostTotal
5Big BazaarAkshayaTrousersWomen/Apparel287017404174
5Big BazaarAkshayaShirtsWomen/Apparel1135013504174
5Big BazaarAkshayaDetergentHousehold0.52701354174
5Big BazaarAkshayaTee ShirtsWomen/Apparel42208804174
5Big BazaarAkshayaInstant NoodlesCanned/Food323694174
The problem. The Id, Shop, Customer and Total are duplicated in each row of the table. The problem gets worse as the number of entries in the bill increases.

1.4The fix: multiple tables

Split the bill into two tables. The first holds the columns that are fixed for the bill. The second holds the variable entries as multiple rows. The Bill ID links the two tables.

ONE BIG TABLE: the red columns repeat in every rowId55555ShopBig BazaarBig BazaarBig BazaarBig BazaarBig BazaarCustomerAkshayaAkshayaAkshayaAkshayaAkshayaItemTrousersShirtsDetergentTee ShirtsNoodlesQty210.543Cost1740135013588069Total417441744174417441744 facts × 5 rows = 20 cellsTWO TABLES: nothing repeats except the linking IdId5ShopBig BazaarCustomerAkshayaTotal4174Id55555ItemTrousersShirtsDetergentTee ShirtsNoodlesQty210.543Cost1740135013588069Id linksfixed for the billone row for each item
Figure 2. The same bill as one big table versus two linked tables
Summary of the idea

Cards with a fixed set of attributes fit one table. Cards with a variable number of entries are split into separate tables, linked by a unique attribute such as the Bill ID. The linking attribute must be unique for each bill, otherwise rows of two bills could be mixed up.

The same split works for any bill. Bill 1 from SV Stores (customer Srivatsan, total 567) has one row in the first table and many in the second: Carrots, Soap, Tomatoes, ..., Milk.

1.5Going deeper

  • Why the link must be unique (extra). If two bills shared Id 5, a lookup of "Id = 5" in the items table would return rows from both, and totals would be wrong.
  • Consistency checks. The bill-level Total must equal the sum of the item Costs, and each Cost must equal Qty × Price. A table lets you check both.
  • One-to-many. One row in table 1 matches many rows in table 2: that is the shape of every "variable number of entries" problem (extra).

1.6Exam tips and common mistakes

Exam tips
  • Name the columns first, then fill one row per card.
  • For a bill, ask "which facts are once per bill and which are once per item?" before drawing any table.
Common mistakes
  • One big table for a bill (Id, Shop, Customer, Total get copied into every row).
  • Linking tables with an attribute that is not unique.
  • Forgetting that every card has a value for every column.

Practice questions (graded-assignment style)

Q1Highest total

Numerical Answer Type (NAT).

In the grade-card table, what is the highest Total?

Solution
Idea

Compare 204, 174, 210.

  • The largest total is 210, on Arshad's card (Id 17).
  • Answer: 210
Q2Maths sum

Numerical Answer Type (NAT).

What is the sum of the Maths marks of the three grade cards?

Solution
Idea

Add 64, 44, 62.

  • 64 + 44 + 62 = 170.
  • Answer: 170
Q3Cells for 20 items

Numerical Answer Type (NAT).

A bill has 20 items. How many cells do the two linked tables use for the 4 bill-level facts plus the linking Id in each item row?

Solution
Idea

4 facts once, plus the Id in each of the 20 rows.

  • 4 + 20 = 24 (the single table would use 4 × 20 = 80).
  • Answer: 24
Q4Why split?

Multiple Choice Question (MCQ): choose the one correct option.

Why is a bill split into two tables?

1
A card cannot have different numbers of rows
2
To avoid copying the bill-level facts into every item row
3
Because tables can have only 4 columns
4
To make Cost smaller
Solution
Idea

Which values repeat in the single table?

  • Id, Shop, Customer and Total repeat in every row, and the repetition grows with the number of items. Two linked tables avoid it.
  • Answer: option 2.
Q5Women/Apparel

Numerical Answer Type (NAT).

How much did Akshaya spend on Women/Apparel items?

Solution
Idea

Find the rows with Id 5 and that category.

  • Trousers 1740 + Shirts 1350 + Tee Shirts 880 = 3970.
  • Answer: 3970
Q6Linking attribute

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
The linking attribute must be unique for each bill
2
The Bill ID appears in both tables
3
The bill Total is stored in every item row of the split tables
4
Table 2 has one row for each item
Solution
Idea

Recall the two-table figure.

  • Statements 1, 2 and 4 are true. The Total belongs to the fixed table (table 1), not the item rows.
  • Answer: options 1, 2 and 4.
Revision overview
Cards to tableCard = unit of information
Attribute = column
Card = row
Shopping billsBill-level: Id, Shop, Customer
Item-level: Item, Qty, Price, Cost
The problemOne table repeats Id, Shop, Total
Worse with more items
TablesLecture 3.1
The fixFixed columns in one table
Item rows in another
The linkBill Id, unique per bill
Savings20 items: 80 cells vs 24
Revision: laying cards out as tables and splitting variable data
Next · Lecture 3.6Pseudocode for Procedures and Parameters, Part 1
02
Lecture 3.6

Pseudocode for Procedures and Parameters, Part 1

Writing a loop once as a procedure, and filling in its blanks with parameters.

Last week the same loop was written again and again with small changes. A procedure is pseudocode written once as a template that works in different situations, with parameters to say which situation we mean.

2.1Why we need procedures

The sum of the boys' Maths marks uses X.Gender == M. What if we want the girls' Maths marks? Only the value checked against X.Gender changes; the remaining pseudocode is identical.

Boys' sum
boys
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == M) {
        Sum = Sum + X.Maths
    }
}
Girls' sum
girls
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == F) {
        Sum = Sum + X.Maths
    }
}

The flowchart changes in just one box too: the decision becomes X.Gender == F instead of X.Gender == M. Copying the whole loop for every small change is wasteful. A procedure lets us write it once.

2.2A procedure to sum Maths marks

SumMaths.pseudo
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
Procedure SumMaths(gen)Sum = 0while (Pile 1 has more cards) {Pick a card X from Pile 1Move X to Pile 2if (X.Gender == gen) {Sum = Sum + X.Maths}}return(Sum)end SumMathsname and argumentargument used in the bodyvalue handed backcloses the procedure
Figure 3. The parts of a procedure
PartIn SumMathsMeaning
NameProcedure SumMathsthe name used to call it
Argumentgenreceives a value on each call
Argument is usedX.Gender == gengen is compared with X.Gender
returnreturn(Sum)hands the value of Sum back
endend SumMathscloses the procedure

Calling the procedure with a parameter: SumMaths(F). The argument variable is assigned the parameter value: the call implicitly starts with gen = F. The procedure returns the value stored in Sum.

The callSumMaths(F)Implicit stepgen = FBody runschecks X.Gender == FReturnsreturn(Sum)
Figure 4. A call fills in the argument, runs the body and returns Sum
Argument and parameter

The name in the procedure heading (gen) is the argument. The value given in the call (F) is the parameter. The call copies the parameter into the argument.

2.3Changing the field: SumMarks(gen, fld)

For the Physics marks the only change is the field examined on the card: X.Physics instead of X.Maths. For Chemistry add up X.Chemistry, for the total X.Total. Writing a new procedure for each field is the same problem again, so pass the field name as a parameter too.

SumMarks.pseudo
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
        }
    }
    return(Sum)
end SumMarks
CallgenfldWhat is added up
SumMarks(F,Chemistry)FChemistryGirls' Chemistry marks
SumMarks(M,Physics)MPhysicsBoys' Physics marks
SumMarks(M,Total)MTotalBoys' Total marks
SumMarks(F,Maths)FMathsGirls' Maths marks
Remember. A parameter can be a value (F) or a field name (Chemistry). Both are just assigned to the argument variables when the call starts. X.fld picks that entry on the card.

2.4Calling a procedure

Use the procedure name like a maths function, as part of an expression, and assign the return value to a variable.

calling-SumMarks
GirlChemSum = SumMarks(F,Chemistry)
BoyChemSum = SumMarks(M,Chemistry)
if (GirlChemSum ≥ BoyChemSum) {
    "Congratulate the girls"
}
else {
    "Congratulate the boys"
}

A procedure may not return a value. For example, a procedure to correct the marks for one subject on a card, Procedure UpdateMarks(CardId, Subject, Marks) ... end UpdateMarks. Its call is a separate statement, not part of an expression: UpdateMarks(17,Physics,88).

EXPRESSIONGirlChemSum =SumMarks(F,Chemistry)a value comes back: assign itSTATEMENTUpdateMarks(17,Physics,88)nothing useful comes back
Figure 5. A call is an expression when a value comes back, and a statement when nothing does
Why procedures help

Procedures modularize pseudocode: the same process is not described again and again. If we improve the code in a procedure, the benefit applies automatically to every call.

2.5Worked examples on eight cards

These eight cards are used in all the examples this week (example data, not from the lecture):

IDGENDERMATHSPHYSICSCHEMISTRY
1M959340
2F944095
3M969441
4F409694
5M429596
6F808281
7F606060
8M707070

2.6Going deeper

  • Call by copying (extra). The parameter is copied into the argument, so changing gen inside the procedure does not change the caller's value.
  • Ignoring the result is a bug. A call like SumMarks(F,Total) on its own line throws the answer away. Assign it.
  • Generalising. SumMaths → SumMarks is the pattern: find what changes between copies and turn each change into a parameter.

2.7Local and global variables: what a procedure can see and keep

A procedure uses variables of its own, such as Sum in SumMarks, and it can also see data that belongs to the program that calls it, such as the deck of cards. Knowing which is which explains why a procedure can be called again and again with different arguments and still give a correct answer.

A. Local variables start fresh on every call

The parameters (gen, fld) and every variable that the procedure sets up inside itself (Sum) are local: they exist only while that call is running. Each new call starts with a new Sum = 0. That is why the following two calls are independent:

local.pseudo
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
        }
    }
    return(Sum)
end SumMarks
  • On the eight cards (with the deck restored between the calls), SumMarks(F,Physics) returns 40+96+82+60=27840 + 96 + 82 + 60 = 278, and SumMarks(M,Physics) returns 93+94+95+70=35293 + 94 + 95 + 70 = 352. The second answer does not include the first.
  • Two different procedures may use the same local name (Sum in SumMarks, Sum in some other procedure) without interfering.
  • Changing a parameter inside the procedure (gen = M) changes only the local copy; the caller's value stays as it was.

B. What goes wrong when the total is kept outside

Suppose Sum = 0 is written once, outside the procedure, so Sum is a shared (global) variable that every call updates:

global-sum.pseudo
Sum = 0
Procedure SumMarks(gen, fld)
    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
        }
    }
    return(Sum)
end SumMarks

Now the first call SumMarks(F,Physics) returns 278278 and leaves Sum = 278. The second call SumMarks(M,Physics) starts from that leftover: it returns 278+352=630278 + 352 = 630, which is wrong. The call that is made first gets the right answer; every later call is contaminated by the earlier ones.

Rule. Initialise the accumulator inside the procedure, so each call begins at 0. If a result must be remembered after the call, the caller saves the returned value in its own variable (GirlPhy = SumMarks(F,Physics), BoyPhy = SumMarks(M,Physics)).

C. Local values versus shared data

Local (parameter or variable set up inside)Shared (the deck of cards, a global variable)
Existsonly during one callbefore and after the call
A change inside the proceduredisappears when the call ends (it cannot change the caller's variable)stays after the call: this is a side effect (see "Side Effects of Procedures")
Examplegen, fld, SumPile 1 and Pile 2: moving cards from Pile 1 to Pile 2 changes the deck for whoever calls next

This is the same distinction as in "Side Effects of Procedures": a procedure that moves the cards from Pile 1 to Pile 2 leaves Pile 1 empty, so a second call finds no cards unless the caller (or the procedure itself) puts them back.

2.8Exam tips and common mistakes

Exam tips
  • To trace a call, first write down the implicit assignments (gen = F, fld = Chemistry), then run the body.
  • To choose a call, name what changes (gender, field) and read the parameters in the heading order.
Common mistakes
  • Mixing up argument (in the heading) and parameter (in the call).
  • Passing the parameters in the wrong order, e.g. SumMarks(Chemistry,F).
  • Using a call without storing or using its return value.

Practice questions (graded-assignment style)

Q1Girls' Chemistry

Numerical Answer Type (NAT).

What does SumMarks(F,Chemistry) return on the eight cards?

Solution
Idea

Add the Chemistry marks of the girls (cards 2, 4, 6, 7).

  • 95 + 94 + 81 + 60 = 330.
  • Answer: 330
Q2Boys' Maths

Numerical Answer Type (NAT).

What does SumMarks(M,Maths) return on the eight cards?

Solution
Idea

Boys are cards 1, 3, 5, 8.

  • 95 + 96 + 42 + 70 = 303.
  • Answer: 303
Q3Which call?

Multiple Choice Question (MCQ): choose the one correct option.

Which call gives the sum of the girls' Physics marks?

1
SumMarks(M,Physics)
2
SumMarks(Physics,F)
3
SumMarks(F,Physics)
4
SumMaths(F)
Solution
Idea

The order is (gender, field).

  • The heading is SumMarks(gen,fld), so the girls' Physics marks are SumMarks(F,Physics) (278 on the eight cards).
  • Answer: option 3.
Q4Statement or expression

Multiple Choice Question (MCQ): choose the one correct option.

UpdateMarks(17,Physics,88) is used as:

1
An expression whose value is stored
2
A separate statement
3
A condition
4
A parameter
Solution
Idea

Does it return a useful value?

  • It returns nothing useful, so the call stands alone as a statement.
  • Answer: option 2.
Q5Argument and parameter

Multiple Select Question (MSQ): select all that apply.

In Procedure SumMarks(gen,fld) called as SumMarks(M,Total), choose the correct statements.

1
gen and fld are the arguments
2
M and Total are the parameters
3
The call implicitly starts with gen = M and fld = Total
4
Total is the argument
Solution
Idea

Argument = name in the heading; parameter = value in the call.

  • Statements 1, 2, 3 are true. Total is a parameter, not an argument.
  • Answer: options 1, 2 and 3.
Q6Why a procedure

Multiple Choice Question (MCQ): choose the one correct option.

What is the main benefit of using one procedure for the boys' and girls' sums?

1
It makes the program run faster
2
The same process is described once; improving it helps every call
3
It removes the need for loops
4
It changes the cards
Solution
Idea

Think of modularising.

  • Procedures modularize pseudocode: write once, call often; an improvement applies to every call.
  • Answer: option 2.
Q1A total kept outside the procedure

Numerical Answer Type (NAT).

On the eight cards of this week, Sum = 0 is written once outside SumMarks(gen, fld), and the procedure never resets it. The deck is restored between calls. The program calls SumMarks(F,Physics) and then SumMarks(M,Physics). What does the second call return?

Solution
Idea

Sum is shared, so the second call starts from the value the first call left behind.

  • Girls' Physics: 40+96+82+60=27840 + 96 + 82 + 60 = 278. After the first call, Sum = 278.
  • Boys' Physics: 93+94+95+70=35293 + 94 + 95 + 70 = 352. The second call keeps adding to 278: 278+352=630278 + 352 = 630.
  • With Sum = 0 inside the procedure, the second call would return 352352.
  • Answer: 630
Q2Local or shared?

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
A variable set up inside a procedure keeps its value from one call to the next.
2
Changing a parameter inside a procedure does not change the argument in the caller.
3
Moving cards from Pile 1 to Pile 2 inside a procedure can be seen by the caller afterwards.
4
Two procedures can each have their own variable called Sum without interfering.
Solution
Idea

Local data is created and discarded with each call; shared data (the deck) outlives the call.

  • 1 ✗ Local variables start afresh on every call. 2 ✓ The parameter is a local copy. 3 ✓ The deck is shared, so this is a side effect. 4 ✓ Local names are private to their procedure.
  • Answer: options 2, 3 and 4.
Q3Why is the second answer wrong?

Multiple Choice Question (MCQ): choose the one correct option.

A student writes GirlChem = SumMarks(F,Chemistry) and then BoyChem = SumMarks(M,Chemistry). The first call gives 330, but BoyChem comes out as 577 instead of 247. What is the most likely cause?

1
The parameter gen was not copied.
2
Sum = 0 is outside the procedure, so the second call continued from 330.
3
The procedure has no return.
4
The field name Chemistry was misspelled.
Solution
Idea

577=330+247577 = 330 + 247: the second answer contains the first.

  • The boys' Chemistry sum is 40+41+96+70=24740 + 41 + 96 + 70 = 247, and 330+247=577330 + 247 = 577. An answer that equals the old total plus the new one points to an accumulator that was never reset.
  • Options 3 and 4 would give an error or a wrong first answer, not a first answer that is right.
  • Answer: option 2.
Revision overview
WhySame loop, small change
Template for many cases
Write once, call often
PartsProcedure name
Arguments (gen, fld)
return(Sum), end name
ParametersCall SumMaths(F)
Implicitly gen = F
A value or a field name
Procedures and parametersLecture 3.6
CallingExpression: x = SumMarks(F,Chemistry)
Statement: UpdateMarks(...)
BenefitModularize pseudocode
Improve once, all calls gain
CheckGirls Chemistry 330
Boys Chemistry 247
Revision: writing a loop once and calling it with parameters
Next · Lecture 3.7Pseudocode for Procedures and Parameters, Part 2
03
Lecture 3.7

Pseudocode for Procedures and Parameters, Part 2

One Maxmarks procedure for any field, and the analysis of top students built on it.

This lecture uses a procedure to answer questions about the top students. The idea: when the same computation is needed for different fields (Maths, Physics, Chemistry, Total), write it once as a procedure and let a parameter name the field.

3.1Analysis of top students

  • Is there a single student who is the best performer across subjects?
  • Is the highest overall total the same as the sum of the highest marks in each subject?

Both questions need the maximum for different fields: Maths, Physics, Chemistry and Total. So one procedure Maxmarks(fld), with the field as a parameter, fits.

3.2Finding the maximum in a given field

As usual keep track of the maximum with a variable: initialise it to 0 and update it whenever you see a bigger value. What is new is that the value being compared is not fixed: the parameter fld decides the field of interest.

Maxmarks.pseudo
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
StartMaxval = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.fld > Maxval?Yes (True)Maxval = X.fldNo (False)
Figure 6. Maxmarks as a flowchart: the Week 2 max flowchart with the field left open
Remember. Calling Maxmarks(Maths) sets fld = Maths, so the test reads X.Maths > Maxval. Calling Maxmarks(Total) makes it X.Total > Maxval. The procedure itself never changes.

3.3Using Maxmarks to compare the totals

Call Maxmarks four times, once for each category, with fld set appropriately. Save each return value in its own variable. Then use the saved values to compare the maximum overall total with the sum of the maximum subject marks.

analysis-of-top-students
MaxMaths = Maxmarks(Maths)
MaxPhysics = Maxmarks(Physics)
MaxChemistry = Maxmarks(Chemistry)
MaxTotal = Maxmarks(Total)
SubjTotal = MaxMaths + MaxPhysics + MaxChemistry

if (MaxTotal == SubjTotal) {
    SingleTopper = True
}
else {
    SingleTopper = False
}
Procedure callValue on the 8 cards
MaxMaths = Maxmarks(Maths)96
MaxPhysics = Maxmarks(Physics)96
MaxChemistry = Maxmarks(Chemistry)96
MaxTotal = Maxmarks(Total)243
SubjTotal = 96 + 96 + 96288
MaxTotal == SubjTotal243 == 288 is False, so SingleTopper = False
Why save the values?

Each call produces a number that is needed later. Putting every return value into its own variable keeps track of the outcomes of the multiple procedure calls, so they can be added and compared.

Sum of the three subject maxima versus the best single total (8 cards)sum of maximaMaths 96 (c3)Phys 96 (c4)Chem 96 (c5)288best total243 (card 6)45the three maxima come from three different cards, so the best total falls short
Figure 7. The best total (243) falls 45 short of the sum of the maxima (288)
What the comparison shows. No card can have a total bigger than the sum of the three subject maximums. So MaxTotal == SubjTotal can only happen when one card holds the highest mark in all three subjects, which means there is a single top student. (This reading is worked out from the pseudocode; the slide only states the question and the code.)

3.4Going deeper

  • Same procedure, four jobs. Using one procedure for four fields avoids describing the same process repeatedly. If we improve the code in the procedure, every call gets the benefit.
  • Parameters fix the context, variables keep the outcomes. The parameter says which field; the saved variables hold what came back.
  • Ties for the top (extra). MaxTotal == SubjTotal says there is a single top student only in the sense "one card holds all three maxima"; it does not say which card. Use the card-id version of Week 2 for that.

3.5Exam tips and common mistakes

Exam tips
  • Make a table of the four calls and their values first; the comparison is then one line.
  • Remember the inequality: a total can never exceed the sum of the subject maxima.
Common mistakes
  • Calling Maxmarks without saving the return value.
  • Starting Maxval at something other than a value below every mark.
  • Reading X.fld as a field literally named "fld".

Practice questions (graded-assignment style)

Q1MaxChemistry

Numerical Answer Type (NAT).

What does Maxmarks(Chemistry) return on the eight cards?

Solution
Idea

Look for the largest Chemistry mark.

  • The largest Chemistry mark is 96, on card 5.
  • Answer: 96
Q2MaxTotal

Numerical Answer Type (NAT).

What does Maxmarks(Total) return on the eight cards?

Solution
Idea

Compute each card's total first.

  • The totals are 228, 229, 231, 230, 233, 243, 180, 210. The maximum is 243 (card 6).
  • Answer: 243
Q3The gap

Numerical Answer Type (NAT).

For the eight cards, what is SubjTotal - MaxTotal?

Solution
Idea

Use 288 and 243.

  • 288 - 243 = 45: no card holds all three maxima.
  • Answer: 45
Q4SingleTopper

Multiple Choice Question (MCQ): choose the one correct option.

For the eight cards, SingleTopper is:

1
True
2
False
3
243
4
Undefined
Solution
Idea

Compare MaxTotal with SubjTotal.

  • 243 == 288 is False.
  • Answer: option 2.
Q5What equality means

Multiple Choice Question (MCQ): choose the one correct option.

MaxTotal == SubjTotal can be True only when:

1
All cards have equal totals
2
One card holds the highest mark in all three subjects
3
The cards are sorted
4
There are exactly two cards
Solution
Idea

No total can exceed the sum of the maxima.

  • A total equals the sum of the three maxima only if that card has the maximum in each subject.
  • Answer: option 2.
Q6Two cards

Numerical Answer Type (NAT).

Pile 1 has cards (90, 85, 80) and (70, 60, 75). What is MaxTotal?

Solution
Idea

Totals are 255 and 205.

  • The larger total is 255 (card 1), equal to SubjTotal = 90 + 85 + 80.
  • Answer: 255
Revision overview
The questionsSingle best performer?
Top total = sum of tops?
Maxmarks(fld)Maxval = 0
if X.fld > Maxval: update
return(Maxval)
Four callsMaths, Physics, Chemistry, Total
Save each return value
Using proceduresLecture 3.7
CompareSubjTotal = sum of three
MaxTotal == SubjTotal ?
8 cards96, 96, 96, 243
288 vs 243: False
BenefitsParameters fix the context
Variables keep the outcomes
Revision: one procedure for the maximum of any field
Next · Lecture 3.8Pseudocode for the Three Prizes Problem
04
Lecture 3.8

Pseudocode for the Three Prizes Problem

A complex problem broken into procedures: top three marks, subject toppers and the three winners.

This lecture works out a complex problem in full detail: awarding three prizes. The trick is to break it into steps, turn the natural units into procedures, and then plug them together.

4.1The three conditions

  1. Basic criterion: total marks. Award prizes to the top 3 students.
  2. Must also be in the top three in at least one subject.
  3. Must select at least one boy and one girl among the three.

Everything starts from the basic pattern: find the top three marks in a category.

4.2Finding the top three marks, step by step

  • The maximum: initialise max to 0, scan the cards, update each time you see a bigger value.
  • The top two: maintain max and secondmax. If the current value is bigger than max, copy max to secondmax and update max. If it is between max and secondmax, leave max alone and update secondmax.
  • The top three: the same idea with one more slot, thirdmax.
slots before: 90, 80, 70bigger than max: 95max90952nd80903rd7080between max and second: 85max90902nd80853rd7080between second and third: 75max90902nd80803rd7075below third: 60max90902nd80803rd7070values shift down like a queue; the old third falls out
Figure 8. The four things that can happen to the three slots when a new value arrives
The values shift down like a queue

A new maximum pushes the old max into second place and the old second into third place. The old third falls out. Update the lowest slot first: third takes second, then second takes max, then max takes the new value. Doing it in the other order would overwrite values before they are copied.

4.3A procedure: top three marks in a subject

TopThreeMarks.pseudo
Procedure TopThreeMarks(Subj)
    max = 0
    secondmax = 0
    thirdmax = 0
    while (Pile 1 has more cards) {
        Pick a card X from Pile 1
        if (X.Subj > max) {
            thirdmax = secondmax
            secondmax = max
            max = X.Subj
        }
        if (max > X.Subj > secondmax) {
            thirdmax = secondmax
            secondmax = X.Subj
        }
        if (secondmax > X.Subj > thirdmax) {
            thirdmax = X.Subj
        }
    }
    return(thirdmax)
end TopThreeMarks
X.Subj > max?Yesthirdmax = secondmaxsecondmax = maxmax = X.SubjNew firstNomax > X.Subj >secondmax?Yesthirdmax = secondmaxsecondmax = X.SubjNew secondNosecondmax > X.Subj >thirdmax?Yesthirdmax = X.SubjNew thirdthree separate ifs; after one updates, the later tests are False
Figure 9. The three cases as a decision chain

In the pseudocode these are three separate if statements. Once one has updated the slots, X.Subj equals that slot, so the later tests are False. It is sufficient to return thirdmax, the third highest mark in the subject. (The procedure ought to return all three values as a list; lists come later in the course.)

Check on the slide. The slide's version of TopThreeMarks (and of the main loop in 4.4) shows Pick a card X from Pile 1 but not Move X to Pile 2. Every earlier loop includes the move, which is what makes the loop end, so these notes keep the code exactly as on the slide and treat the move as understood.

4.4The three prizes algorithm

The prize winners are the top three totals, but only among students who are in the top three in at least one subject. (The boy and girl requirement is dealt with later.) Again we maintain max, secondmax, thirdmax, now together with the card ids maxid, secondmaxid, thirdmaxid, because at the end we need to know who the winners are.

1 Initialisemaxima 0, ids −12 Subject thirdsmaths3 phys3 chem33 Scan cardsonly SubjectTopper4 UpdateX.Total + ids
Figure 10. The four stages of the algorithm
Who is in the top three of a subject?

A card is in the top three of a subject exactly when its mark is at least the third highest mark of that subject. That is why we record maths3, phys3 and chem3 first and compare each card with them before updating max, secondmax, thirdmax.

three-prizes.pseudo
max = 0
secondmax = 0
thirdmax = 0
maxid = -1
secondmaxid = -1
thirdmaxid = -1

maths3 = TopThreeMarks(Maths)
phys3 = TopThreeMarks(Physics)
chem3 = TopThreeMarks(Chemistry)

while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    if (SubjectTopper(X,maths3,phys3,chem3)) {
        if (X.Total > max) {
            thirdmax = secondmax
            thirdmaxid = secondmaxid
            secondmax = max
            secondmaxid = maxid
            max = X.Total
            maxid = X.Id
        }
        if (max > X.Total > secondmax) {
            thirdmax = secondmax
            thirdmaxid = secondmaxid
            secondmax = X.Total
            secondmaxid = X.Id
        }
        if (secondmax > X.Total > thirdmax) {
            thirdmax = X.Total
            thirdmaxid = X.Id
        }
    }
}
Names on the slides. The slides write the first of these variables as maths3 in one place and math3 in another, and call the procedure as SubjectTopper(X,M,C,P) although its heading is (Card,MMark,PMark,CMark). These notes use maths3, phys3, chem3 consistently and pass the three third-highest marks in the order of the heading.

4.5The procedure SubjectTopper

Compare each subject's marks on the card with the third highest mark. The marks are passed explicitly as parameters. One or more comparisons should succeed, which is what the or operator means.

SubjectTopper.pseudo
Procedure SubjectTopper(Card,MMark,PMark,CMark)
    if (Card.Maths ≥ MMark or
        Card.Physics ≥ PMark or
        Card.Chemistry ≥ CMark) {
        return(True)
    }
    else {
        return(False)
    }
end SubjectTopper
A shortcut for Boolean procedures. The value returned is a Boolean: True or False. Typically we would call it as if (SubjectTopper(X,M,C,P) == True). Since the return value is already Boolean, we can simply write if (SubjectTopper(X,M,C,P)).

4.6Boundary conditions

A good solution has to anticipate unexpected situations in the data. The lecture raises two.

1 · All winners of the same genderExclude the third prize winner and repeat the process. Repeat until we get three prize winners with at least one boy and one girl. Open question from the lecture: will this always give three valid prize winners?
2 · TiesWhat if there are ties? How many ties can we tolerate? Does it depend on first, second or third position? The lecture leaves these as questions to think about.
StartFind the three prize winnersAt least one boyand one girl?YesAward the prizesNoExclude the third winnerrepeat until the three winners include a boy and a girl
Figure 11. Handling the gender requirement by excluding the third winner and repeating
Ties in the code. Every comparison in the code above is strict (>). So a later card whose total equals max, secondmax or thirdmax does not take that slot: the card that arrived first stays. This follows from the code as written; the slide only poses the questions.

4.7When the code gives a wrong answer: ties (extra)

Because every comparison is strict, TopThreeMarks effectively finds the third highest distinct mark. That is fine when marks are all different, but ties can break the idea:

Marks in the subjectTopThreeMarks returnsWhy it matters
96, 95, 9494correct: the third highest mark
96, 96, 95, 9494the repeated 96 is ignored, so 94 is returned although only two cards are above it
90, 90, 900thirdmax stays 0, so every card passes SubjectTopper

So ties need a deliberate choice of rule (the lecture leaves this open): for example, decide whether equal marks share a place, and change the comparisons (> versus ≥) to match.

4.8Going deeper

  • Break big problems into procedures. The prize problem is one loop plus two procedures (TopThreeMarks, SubjectTopper); each is small enough to check on its own.
  • Will the exclusion always work? (extra) No: if fewer than three eligible cards remain, or all eligible cards have the same gender, repeating cannot produce a boy and a girl. A real solution must say what to do then.
  • Total before subject. Card 6 has the best total but is not eligible: the subject condition filters first, then the total ranks.

4.9Exam tips and common mistakes

Exam tips
  • Compute the three subject thresholds (maths3, phys3, chem3) first, then mark each card Topper or not, then rank only the toppers.
  • Keep each slot as (total, id) pairs so the winners can be read off.
Common mistakes
  • Updating the slots in the wrong order and overwriting values before copying them.
  • Forgetting to initialise the ids to -1.
  • Awarding a prize to a card with the best total that is not a subject topper.
  • Ignoring that all three winners can be of one gender.

Practice questions (graded-assignment style)

Q1maths3

Numerical Answer Type (NAT).

What does TopThreeMarks(Maths) return on the eight cards?

Solution
Idea

The three highest Maths marks are 96, 95, 94.

  • The third highest Maths mark is 94 (card 2).
  • Answer: 94
Q2Subject toppers

Multiple Select Question (MSQ): select all that apply.

With maths3 = phys3 = chem3 = 94, which cards are subject toppers?

1
Card 1
2
Card 4
3
Card 6
4
Card 8
Solution
Idea

A card passes if any one mark is at least 94.

  • Card 1 has Maths 95; card 4 has Physics 96 and Chemistry 94.
  • Cards 6 (80, 82, 81) and 8 (70, 70, 70) have no mark of 94 or more.
  • Answer: options 1 and 2.
Q3First prize

Multiple Choice Question (MCQ): choose the one correct option.

Who wins the first prize in the eight-card run?

1
Card 6 (total 243)
2
Card 5 (total 233)
3
Card 3 (total 231)
4
Card 4 (total 230)
Solution
Idea

Card 6 has the best total but is not eligible.

  • Among the eligible cards the highest total is 233, on card 5.
  • Answer: option 2.
Q4Third prize id

Numerical Answer Type (NAT).

In the same run, which card id gets the third prize?

Solution
Idea

The third-highest eligible total is 230.

  • The winners are 5 (233), 3 (231), 4 (230): the third prize goes to card 4.
  • Answer: 4
Q5Same gender

Multiple Choice Question (MCQ): choose the one correct option.

If card 4 were a boy, after excluding card 4 the third prize winner becomes:

1
Card 1
2
Card 2
3
Card 6
4
Card 7
Solution
Idea

Eligible cards are 1, 2, 3, 5; take the top three totals.

  • The top three totals are card 5 (233), card 3 (231) and card 2 (229, a girl), so the condition now holds.
  • Answer: option 2.
Q6Ties in the code

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about the code as written.

1
A later card whose total equals thirdmax does not take the slot
2
Every comparison is strict (>)
3
TopThreeMarks of 90, 90, 90 returns 90
4
The card that arrived first stays on a tie
Solution
Idea

Strict comparisons never replace an equal value.

  • Statements 1, 2 and 4 follow from the strict comparisons.
  • Statement 3 is false: for 90, 90, 90 the procedure returns 0 (extra).
  • Answer: options 1, 2 and 4.
Revision overview
ConditionsBasic: total marks
Top three in some subject
At least one boy and one girl
Top three marksmax, secondmax, thirdmax
A new value shifts the slots
TopThreeMarks returns thirdmax
SubjectTopperCompare with third highest
Card.Maths ≥ MMark or ...
Returns True or False
Three prizesLecture 3.8
The algorithmInit ids to -1
maths3, phys3, chem3
Update totals and ids
8 cardsWinners: 5, 3, 4
Card 6 not eligible
BoundariesSame gender: exclude third, repeat
Ties: how many tolerated?
Revision: breaking a complex problem into procedures
Next · Lecture 3.9Side Effects of Procedures
05
Lecture 3.9

Side Effects of Procedures

What a procedure changes besides its return value, and the contract that says what it promises.

A procedure can do more than return a value: it can change data while it runs. This lecture is about noticing those changes, called side effects, and about writing down what a procedure promises.

5.1Passing the deck of cards

The procedure SumMarks(gen,fld) works for one fixed set of cards, the cards in Pile 1. What about any set of cards? Pass the deck through a third parameter.

SumMarks-with-Deck.pseudo
Procedure SumMarks(gen,fld,Deck)
    Sum = 0
    while (Deck has more cards) {
        Pick a card X from Deck
        Move X to SeenDeck
        if (X.Gender == gen) {
            Sum = Sum + X.fld
        }
    }
    return(Sum)
end SumMarks
  • Third parameter Deck: the loop now runs over the given deck.
  • New variable SeenDeck plays the role of the second pile.
  • Deck is modified as the procedure executes: cards move from Deck to SeenDeck.
  • At the end Deck is empty! The procedure should also restore Deck from SeenDeck.

The version that restores the deck adds one line before the return:

SumMarks-restoring-Deck.pseudo
Procedure SumMarks(gen,fld,Deck)
    Sum = 0
    while (Deck has more cards) {
        Pick a card X from Deck
        Move X to SeenDeck
        if (X.Gender == gen) {
            Sum = Sum + X.fld
        }
    }
    Restore Deck from SeenDeck
    return(Sum)
end SumMarks
Deck and SeenDeck, card 1 starts on topBeforeDeck1234SeenDeckemptyAfter 2 cardsDeck34SeenDeck21End of loopDeckemptySeenDeck4321RestoredDeck4321SeenDeckemptySeenDeck holds the cards in reverse orderso a handed-back deck is reversed unless we say otherwise
Figure 12. The deck is emptied into SeenDeck, which holds the cards in reverse order
Is that enough?

The lecture asks what the status of Deck is after the procedure. Each card should be the same as before. But is the sequence of cards the same? Perhaps not. It depends what we mean by "restore": SeenDeck would normally be in reverse order.

5.2Side effects

Definition: side effect

A side effect is when a procedure modifies some data during its computation.

Here the sequence of cards may be disturbed. Does it matter? It depends:

Harmlessadding marks:order does notmatterThe goalsorting cardsby Total MarksUndesirablea sorted deckcomes backrearrangedForbiddenFindMatch mustleave the wordsuntouched
Figure 13. The same kind of change can be harmless, wanted, harmful or forbidden
  • Not important: adding marks does not depend on how the cards are arranged.
  • The side effect is the goal: a procedure to arrange cards in decreasing order of Total Marks exists to change the order.
  • Could be undesirable: we pass a deck in decreasing order of Total Marks; afterwards it is randomly rearranged.
  • Not tolerated: pronoun matching: FindMatch must leave the words and their positions untouched.

5.3Interface versus implementation

Each procedure comes with a contract.

Contract part 1: functionalityWhat parameters will be passed, and what is expected in return.
Contract part 2: data integrityCan the procedure have side effects? Is the nature of the side effect predictable? For instance, the deck is reversed.
CONTRACT = INTERFACEparameters passedvalue returnedside effects: possible? predictable?must not changeIMPLEMENTATIONthe code insideloops, variable names, speedfree to change
Figure 14. The contract is the interface; the code inside is the implementation
The rule

The contract specifies the interface. We can change the procedure's implementation (its code) provided the interface is unaffected.

5.4Side effects in text: pronoun matching

Another task: associating personal pronouns with nouns in a passage of text. Fix a pronoun, search the text before the pronoun backwards, and stop at the nearest name. Write it as a procedure FindMatch(before, pronoun, after): the text before the pronoun, the pronoun, and the text after it.

FindMatch(before, He, after): search backwardsSwaminathanwasreluctanttoopenhiseyesHesearch backwards, stop at the nearest namenamepronounthe procedure only reads the words: no side effect
Figure 15. For the pronoun He, search backwards until the nearest name, Swaminathan
No side effects here. FindMatch should not disturb before and after: the sequence of words and their positions must stay as they are. No side effects should happen, unlike the card deck where some change was acceptable.

5.5Going deeper

  • Order matters only sometimes. A sum is the same in any order, but a "first match" or a sorted list is not. Ask whether the answer depends on order before you accept a reordering side effect (extra).
  • Write the side effect in the contract. "The deck is reversed" is fine if it is promised and predictable.
  • Interface changes break callers. Adding a parameter or changing a promised side effect breaks every call that depends on the old contract.

5.6Exam tips and common mistakes

Exam tips
  • For a side-effect question, ask three things: what data changes, does the order matter to the caller, and does the contract promise it?
  • When asked "may we change the code?", check the interface first: parameters, return value, side effects.
Common mistakes
  • Forgetting to restore the deck after the loop (the deck is left empty).
  • Assuming the restored deck has the same order as before.
  • Changing the interface and thinking it is just a code change.

Practice questions (graded-assignment style)

Q1Cards left

Numerical Answer Type (NAT).

In the trace of SumMarks(F,Chemistry,Deck), how many cards are left in Deck after card 3 has been moved?

Solution
Idea

8 cards, 3 moved.

  • 8 - 3 = 5 cards remain; SeenDeck is 3, 2, 1 from top to bottom.
  • Answer: 5
Q2SeenDeck order

Multiple Choice Question (MCQ): choose the one correct option.

After the loop, the cards in SeenDeck from top to bottom are:

1
1, 2, ..., 8
2
8, 7, ..., 1
3
Empty
4
Random
Solution
Idea

Each new card goes on top of the previous ones.

  • The last card moved (8) ends on top, so the order is reversed: 8, 7, ..., 1.
  • Answer: option 2.
Q3Is it acceptable?

Multiple Select Question (MSQ): select all that apply.

Which side effects are acceptable?

1
SumMarks returns the deck in reverse order
2
A sorting procedure reorders the cards
3
FindMatch changes the order of words
4
FindMatch only reads the words
Solution
Idea

Does the order matter to the caller?

  • Options 1 and 2 are fine (order is irrelevant for a sum; reordering is the goal of a sort). Option 3 is forbidden; option 4 has no side effect at all.
  • Answer: options 1, 2 and 4.
Q4May we change it?

Multiple Select Question (MSQ): select all that apply.

Which changes to SumMarks keep the interface unchanged?

1
Rename the variable Sum to Total
2
Rewrite the loop faster, returning the same sum
3
Add a fourth parameter
4
Change the promised side effect
Solution
Idea

Interface = parameters, return value, side effects.

  • Options 1 and 2 change only the implementation. Options 3 and 4 change the interface.
  • Answer: options 1 and 2.
Q5Which match?

Multiple Choice Question (MCQ): choose the one correct option.

For the pronoun He in "Swaminathan was reluctant to open his eyes. He considered ...", FindMatch returns:

1
eyes
2
his
3
open
4
Swaminathan
Solution
Idea

Search backwards for the nearest name.

  • eyes is not a name and his is a pronoun; the nearest name is Swaminathan.
  • Answer: option 4.
Q6The contract

Multiple Choice Question (MCQ): choose the one correct option.

Which is part of a procedure's contract?

1
The names of its local variables
2
Its parameters, its return value and its side effects
3
The speed of its loop
4
The colour of its flowchart
Solution
Idea

Functionality plus data integrity.

  • The contract fixes the interface: what goes in, what comes out, and what data may change.
  • Answer: option 2.
Revision overview
Passing a deckThird parameter Deck
SeenDeck as second pile
Deck empty, then restore
Side effectProcedure modifies data
Order of cards may change
SeenDeck is in reverse
Does it matter?Adding marks: no
Sorting: it is the goal
Pronoun matching: never
Side effectsLecture 3.9
The contractFunctionality
Data integrity
Specifies the interface
The ruleChange implementation freely
Keep the interface
FindMatchNo side effects allowed
Revision: noticing what a procedure changes and promising it in a contract
Next · All lecturesWeek 3 Summary Sheet
06
All lectures

Week 3 Summary Sheet

One page to revise all of Week 3: tables, procedures with parameters, using procedures, the three prizes and side effects.

The big picture

Lecture 3.1 · Tables
  • Each attribute is a column, each card is a row.
  • Variable-size entries split into tables linked by a unique Id.
Lecture 3.6 · Procedures, part 1
  • A procedure is a template; arguments (gen, fld) get the parameters of the call.
  • Call as an expression, or as a statement if nothing is returned.
Lecture 3.7 · Procedures, part 2
  • Maxmarks(fld) finds the max of any field.
  • Four calls, four saved values, then compare MaxTotal with SubjTotal.
Lecture 3.8 · Three prizes
  • Keep three maxima and their ids.
  • TopThreeMarks and SubjectTopper are the natural procedures; plan for same-gender winners and ties.
Lecture 3.9 · Side effects
  • Passing a Deck changes it; a side effect is data modified by a procedure.
  • The contract (interface) lists parameters, return value and side effects.
Always
  • Read the contract.
  • Change the code inside freely, never the promises.

Parts of procedures and calls

PartExampleMeaning
HeadingProcedure SumMarks(gen,fld)Names the procedure and its arguments
Argumentgen, fldVariables that receive values when the call starts
ParameterF, ChemistryThe values given in the call, copied into the arguments
Returnreturn(Sum)Hands a value back to the caller
Endend SumMarksCloses the procedure
Call as expressionGirlChemSum = SumMarks(F,Chemistry)Use the returned value, usually assign it
Call as statementUpdateMarks(17,Physics,88)Nothing useful comes back
Boolean callif (SubjectTopper(X,maths3,phys3,chem3))A procedure returning True or False can be the condition itself

The procedures of this week

ProcedureArgumentsReturnsNotes
SumMathsgenSumSum of Maths marks for one gender
SumPhysicsgenSumSame, with X.Physics
SumMarksgen, fldSumGender and field are parameters
UpdateMarksCardId, Subject, Marksnothing usefulCalled as a statement
MaxmarksfldMaxvalMaximum of any field
TopThreeMarksSubjthirdmaxThird highest mark in a subject
SubjectTopperCard, MMark, PMark, CMarkTrue / FalseTop three in at least one subject
SumMarks (with a deck)gen, fld, DeckSumMoves cards to SeenDeck and restores Deck; order may change
FindMatchbefore, pronoun, afterthe match for the pronounNo side effects allowed

The slot update to remember

shift-down-then-take-first
if (X.Total > max) {
    thirdmax = secondmax
    thirdmaxid = secondmaxid
    secondmax = max
    secondmaxid = maxid
    max = X.Total
    maxid = X.Id
}
Order matters. Update the lowest slot first: third takes second, then second takes max, then max takes the new value. Doing it in the other order would overwrite values before they are copied.

Which tool when?

SituationTool
Cards with a fixed set of attributesOne table: attribute = column, card = row
Entries vary in number, such as a billTwo tables linked by a unique Id
Same loop with a small changeA procedure with parameters
A value is needed backreturn(...), then assign: x = Proc(...)
Nothing useful to returnA call used as a separate statement
Top three of something, and whoThree slots plus three ids, strict >
Who is eligible?A Boolean procedure: if (Proc(...))
Does the procedure change its data?State it in the contract (interface)

Common mistakes

Ignoring the return value
  • A call like SumMarks(F,Total) on its own line throws the answer away. Assign it.
Argument and parameter mixed up
  • The argument is the name in the heading; the parameter is the value in the call.
Ids not initialised
  • Set maxid, secondmaxid, thirdmaxid to -1 before the loop, like the maxima to 0.
Forgetting to restore the deck
  • After a loop over Deck, it is empty. Restore it from SeenDeck, and remember the order may differ.
Changing the interface
  • Adding a parameter or changing a promised side effect breaks every caller.
One big table for a bill
  • Id, Shop, Customer and Total get copied into every row. Use two linked tables.
Ties and top-three (extra)
  • Strict comparisons ignore equal marks: 90, 90, 90 leaves thirdmax = 0. Decide a tie rule first.
Back to top