SECTION 08 / 15

Procedures, parameters and return values

2 min read
On this page 1 headings

A procedure is a named set of steps we can reuse. Think of asking a helper to do one well-defined job. Parameters tell the helper which version of the job to do. A return value brings the answer back.

The same SumMarks procedure can select a gender value and a mark field.
The same SumMarks procedure can select a gender value and a mark field.

Separate a value from a field name

In SumMarks(F, Mathematics), F is a value used in a comparison with Gender. Mathematics is the name of the field to extract. Inside the procedure, the parameter GenderValue receives F and Field receives Mathematics. X[Field] means “read the field whose name is stored in Field”.

Procedure SumMarks(Rows, GenderValue, Field)
    Sum = 0
    for each row X in Rows {
        if (X.Gender == GenderValue) {
            Sum = Sum + X[Field]
        }
    }
    return Sum
End Procedure
GirlsMaths = SumMarks(Scores, "F", "Mathematics")
BoysMaths = SumMarks(Scores, "M", "Mathematics")
REAL COURSE DATA · FOLLOW THE PROCEDURE

Call SumMarks with different parameters

Read the current record, check the explanation, and watch the variables. Use Back to revisit any step.

Ready

CURRENT RECORD

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Start at the first step. Watch the current row and the values we remember.

CallReturned value
SumMarks(Scores,F,Mathematics)951
SumMarks(Scores,M,Mathematics)1220
SumMarks(Scores,F,Chemistry)1064
SumMarks(Scores,M,Chemistry)1250

Sum starts at zero on every call. Changing parameters does not require rewriting the loop. return Sum sends the computed number to the caller; writing it into GirlsMaths preserves it for later. Equal code does not mean equal answers when the parameters differ.

The groups contain 13 F and 17 M records. Raw sums alone do not establish which group has a higher average. Divide each group sum by its own count for that question.

Try it yourself

Which argument is an attribute name in SumMarks(F,Chemistry)?

Show explained answer

Chemistry. F is the category value to compare.

Try it yourself

What does return Sum do?

Show explained answer

It sends the computed Sum back to the code that called the procedure.

Try it yourself

Should Sum keep its value from the previous call?

Show explained answer

No. Each new sum computation initializes its own Sum to zero.

Try it yourself

Do larger total group marks necessarily mean a larger average?

Show explained answer

No. Groups can have different numbers of records.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑