Functions and Procedures Explained with Pseudocode: Programming Fundamentals (12)
Learn procedures and functions in pseudocode: parameters by value and by reference, return values, scope, and how to split a program into subprograms.
A subprogram is a named block of instructions that does one job. You write it once and run it as many times as you need by calling its name. There are two kinds. A procedure does a job and gives nothing back. A function does a job and gives back one value.
After this lesson, you can split a long program into small subprograms, pass data into them, and get results out of them. You will also know which of your variables a subprogram can see and change.
In this lesson you will:
- Write procedures and functions in pseudocode, and call them.
- Pass parameters by value and by reference, and know when to use each one.
- Return a value from a function.
- Find the scope of a variable, and spot shadowing.
- Build a small toolkit of subprograms that work on arrays.
It takes about 45 minutes. Every program on this page runs in your browser, so you can change it and press Run.
Why split a program
Some problems are too big to solve in one piece. You can break them into smaller problems and solve each one in its own subprogram. The course slides list three reasons to do this:
- Modularization. Each part of the program lives in its own block, so you can read and fix one part at a time.
- Abstraction. Once a subprogram works, you can use it without thinking about how it works inside. You only need its name, what it takes and what it gives back.
- Reuse. You write the code once and call it from many places. If you find a bug, you fix it in one place.
You already use subprograms that other people wrote. In Strings you called Length, Upper and Substring in pseudocode, or print and input in Python. From now on you write your own.
This matters even more today, because AI agents organize the code they write in functions. When you review that code, you read it one function at a time. The first line of a function tells you what it needs, what it gives back, and which of your variables it can change. If you can read that line, you can check the AI’s work in minutes instead of hours.
Procedures do a job
A procedure has four parts:
- Header. The keyword
Procedure, a descriptive name, and the parameters in parentheses. - Local declarations. The variables that only exist inside the procedure.
- Body. The instructions that run when someone calls it.
- Call. To run it, write its name and the values to send, as a statement on its own line.
In StepCode, subprograms go outside the main program, after EndProgram. Here is the example from class: a procedure that writes a multiplication table. It is the For loop from Loops, now with a name. The program calls it twice with different numbers.
When you type 7, you should see:
Which table do you want?
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
And the next one:
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
The procedure did its job twice, and it gave nothing back to the program. Its only effect is the text it writes.
Functions return a value
A function is the same as a procedure with one addition. It gives back a value, called the return value. In the header, you write the type of that value after a colon. Inside, the Return instruction ends the function and sends the value back.
Because a function gives back a value, you use its call as a value. You can store it in a variable, write it, or put it inside an expression. The class activity asks for the absolute value of a number (its distance from zero, so -42 becomes 42) in both forms. StepCode already has Abs (see Operators and expressions), so writing your own is practice. Compare them:
When you type -42, you should see:
Type a whole number:
The procedure says 42
The function returned 42
Twice the absolute value is 84
The procedure can only write the answer. The function hands the answer back, so the program can multiply it by 2. That is why functions are more flexible when you need a result for later.
You may also see functions written in the PSeInt style, Function result <- Absolute(x As Integer), where you assign the answer to the result variable instead of using Return. StepCode accepts both. This series uses Return, which is closer to Python, C and JavaScript.
Here is the same function in Python:
def absolute(x: int) -> int:
if x < 0:
return -x
return x
print(absolute(-42)) # 42
Parameters carry data in
A parameter is a variable in the header of a subprogram. It receives a value when someone calls the subprogram. The course uses two names for the two sides of a call:
- Formal parameters are the names in the definition. In
Procedure ShowTable(n As Integer),nis a formal parameter. - Actual parameters, also called arguments, are the real values in the call. In
ShowTable(n + 1), the argument is the value ofn + 1.
Each formal parameter acts like a local variable that starts with the value of its argument. The program matches them by position. The first argument goes to the first parameter, the second to the second, and so on.
By value or by reference
There are two ways to send an argument. The difference decides whether the subprogram can change your variable.
- By value. The subprogram gets a copy. If it changes the copy, your variable stays the same. This is the default for simple types like
Integer,RealandString. - By reference. The subprogram gets your variable itself, under another name (an alias). If it changes the parameter, your variable changes too. In StepCode, you write
ByRefafter the type.
Two columns run the same steps. By value: the program has a box n holding 5. The call copies 5 into a new box p, p becomes 6, and when the procedure ends p disappears, so n is still 5. By reference: p is a second name for the box of n, so when p becomes 6, n is 6 too, and it stays 6 after the procedure ends.
p becomes 6. By value, only the copy changes. By reference, the one shared box changes.
This program from the course wiki starts with n equal to 5 and calls two procedures that add 1:
You should see:
Inside IncrementCopy, p is 6
Back in the program, n is 5
Inside IncrementOriginal, p is 6
Back in the program, n is 6
IncrementCopy changed its copy to 6, but n was still 5 afterward. IncrementOriginal changed p, and p was n, so n became 6.
Use ByRef only when the job of the subprogram is to change your variable. Swapping two values, the job you did with a temp variable in Variables and data types, is the classic case:
When you type 3 and then 8, you should see:
Type A:
Type B:
A is now 8
B is now 3
Without ByRef, Swap would exchange two copies, and a and b would not change. The final project uses ByRef the same way, to add points to the score.
A note for Python: Python passes arguments in a third way, called pass by assignment. Numbers and strings behave like by value. Lists can be changed inside the function, but if you assign a new list to the parameter, the caller does not see it. When you read Python that an AI wrote, check which of the two happens.
Scope and shadowing
The scope of a variable is the part of the program where you can use it. A variable you declare inside a subprogram is a local variable. It is born when the subprogram starts and disappears when it ends. Nothing outside can see it.
Many languages also have global variables, declared outside every subprogram and visible everywhere. Python has them. Pseudocode in this course does not: a subprogram only sees its parameters and its own local variables. If it needs data from the program, the program must pass it in.
What if a subprogram declares a variable with the same name as one in the program? Then you get shadowing. Inside the subprogram, the local variable hides the outer one. They are two different variables that happen to share a name.
Each call gets its own box of variables, called a frame, on top of the caller’s frame. Step through the next program to see both total variables live in different frames.
The program stores 100 in its variable total and calls Average(4, 8). The call puts a new box for Average on top, with a = 4 and b = 8. Average declares its own total and stores 12 in it, while the program's total is hidden but still 100. Return sends 6 back and the box of Average disappears with its variables. The program writes 6, and then writes that its total is still 100.
Average stores 4 + 8 = 12 in its own total. The program's total still holds 100.
You should see:
Average of 4 and 8: 6
total in the program is still 100
The total inside Average held 12 for a moment and then disappeared. The total in the program kept its 100. Shadowing is legal, but it confuses readers. Give local variables names that say what they hold.
Build an array toolkit
Now put it all together. You will build the toolkit from the unit 6 practice guide: a set of subprograms that read, print, add, search, reverse and sort an array of whole numbers.
Arrays work differently from simple types. When you pass an array, the subprogram works on the original, not on a copy. The slides call this the default for structured types. You do not need ByRef, and a procedure can fill or sort your array directly. In the header, write the type followed by empty brackets, like list As Integer[]. In the main program, you declare the array as in Arrays, with Define and Dimension.
1. Read and print the array
ReadArray is a function. It fills the array and returns how many numbers it read. It uses a small helper function, Smaller, to never read more than 10. PrintArray is a procedure that writes the numbers on one line.
When you type 5, then 4, 1, 5, 3 and 2, you should see:
How many numbers (max 10)?
The array is: 4 1 5 3 2
If you type a count bigger than 10, Smaller turns it into 10. Notice that ReadArray filled numbers in the program without ByRef, because arrays are shared with the subprogram.
2. Add sum, max and min
Each new question gets its own small function. Each one takes the array and the count, and returns one number.
With the same inputs, you should see:
How many numbers (max 10)?
The array is: 4 1 5 3 2
The sum is: 15
The biggest is: 5
The smallest is: 1
3. Search for a number
Search returns the position of a number, or -1 when the number is not in the array. A function can have more than one Return. The first one that runs ends the function, so the search stops as soon as it finds a match.
With the same inputs and 5 as the number to search, you should see:
How many numbers (max 10)?
The array is: 4 1 5 3 2
The sum is: 15
The biggest is: 5
The smallest is: 1
Number to search:
Its position is: 3
If you search for a number that is not there, like 9, the last line says Its position is: -1.
4. Reverse and sort
The last two are procedures, because their job is to change arrays. Reverse copies the array backward into a second array. Sort uses the bubble sort from the arrays lesson, and it calls Swap to exchange two neighbors. One subprogram calling another is normal. It is how big programs are built.
With the same inputs and 5 as the number to search, you should see:
How many numbers (max 10)?
The array is: 4 1 5 3 2
The sum is: 15
The biggest is: 5
The smallest is: 1
Reversed: 2 3 5 1 4
Sorted: 1 2 3 4 5
Number to search:
Its position is: 5
The search now says 5, because the program searched after sorting, and 5 moved to the last position. Read the main program again. It is short, and every line says what it does. That is the real win of subprograms.
Common mistakes
StepCode checks your program before it runs. These are the messages you will meet most often with subprograms.
If you see "total" is not declared. inside a subprogram, it means you used a variable from the main program. Subprograms cannot see it. Pass the value in as a parameter.
If you see Parameter "x" is ByRef: pass a variable here, not a computed value., it means you called something like Swap(a + 1, b). A ByRef parameter needs a real variable to change. Store the value in a variable first, then pass the variable.
If you see "ShowTotal" is a subprogram with no return value: it cannot be used as a value., it means you wrote a <- ShowTotal(); with a procedure. Only functions give back a value. Turn it into a function with Return, or call it on its own line.
If you see "Swap" needs 2 arguments and you gave it 1., count the values in the call. They must match the parameters in the header, in the same order.
If the program stops with Function "Grade" ended without a result: assign its result or use "Return"., some path through the function has no Return. This happens with an If that returns only when the condition is true. Make sure every path ends in a Return.
Procedure or function
Use this table when you are not sure which one to write.
| Procedure | Function | |
|---|---|---|
| Gives back a value | No | Yes, one value with Return |
| How you call it | As a statement on its own line | Inside an expression or an assignment |
| Good for | Writing output, filling or sorting arrays, swapping | Calculations, checks, searches |
| Example | PrintArray(numbers, count); |
total <- Sum(numbers, count); |
A function that also writes to the screen or changes its arguments is legal, but it surprises readers. Try to keep functions to one thing: take values in, give one value back.
Subprograms are also not loops. A loop repeats instructions in one place. A subprogram lets you run the same instructions from many places.
Practice exercises
Try each one in an editor before you open the solution.
Exercise 1: names that lie
This one comes from the practice guide. The function names lie on purpose. Add subtracts, Subtract adds, and Both uses Or. Read the bodies, then write down what each line prints. Press Run to check.
You should see:
-9
4
6
True
The lesson: a function does what its body says, not what its name says. Check this every time you review code an AI named for you.
Exercise 2: mirror text
Write a function that takes a text and returns the text followed by its reverse. For Hello how are you, it returns Hello how are youuoy era woh olleH. This was a question on the second exam of the course. It reuses the reverse loop from Strings.
Solution
When you type Hello how are you, you should see:
Type a text:
Hello how are youuoy era woh olleHExercise 3: change a date format
Write a function that takes a date as yyyy/mm/dd and returns it as dd/mm/yyyy. For 1998/12/10, it returns 10/12/1998. Years always have 4 characters, and months and days have 2.
Solution
When you type 1998/12/10, you should see:
Type a date as yyyy/mm/dd:
10/12/1998Exercise 4: normalize an array
Write a procedure that normalizes an array of 5 numbers with the min max method. Find the smallest and the biggest value. Subtract the smallest from every element, then divide each element by the difference between the biggest and the smallest. For 1 2 5 3 4, the result is 0 0.25 1 0.5 0.75.
Solution
When you type 1, 2, 5, 3 and 4, you should see:
0 0.25 1 0.5 0.75 What you learned
- A procedure does a job and gives nothing back. A function does a job and returns one value with
Return. - Parameters carry data in. By value sends a copy.
ByRefsends the variable itself, so the subprogram can change it. Arrays are always shared. - Local variables live only inside their subprogram. A local variable with the same name as an outer one shadows it.
- A good main program is short and reads like a list of steps, because the details live in subprograms.
Next steps
Every program so far forgets everything when it ends. In the next lesson, Files, you save data to text files and read it back, so your programs can remember.