---
title: "Functions and Procedures Explained with Pseudocode: Programming Fundamentals (12)"
date: "2026-11-01"
description: "Learn procedures and functions in pseudocode: parameters by value and by reference, return values, scope, and how to split a program into subprograms."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-procedures-and-functions/"
author: "Rolando Andrade"
---

# 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](/blog/programming-fundamentals-strings/#the-tools-for-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](/blog/programming-fundamentals-loops/#the-for-loop), now with a name. The program calls it twice with different numbers.

**Multiplication table procedure** (StepCode)

```stepcode
Program MultiplicationTables
    Define n As Integer;
    Write "Which table do you want? ";
    Read n;
    ShowTable(n);
    Write "And the next one:";
    ShowTable(n + 1);
EndProgram

// Writes the multiplication table of n, from 1 to 5
Procedure ShowTable(n As Integer)
    Define i As Integer;
    For i <- 1 To 5 Step 1 Do
        Write n, " x ", i, " = ", n * i;
    EndFor
EndProcedure
```

When you type `7`, you should see:

```text
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](/blog/programming-fundamentals-operators-and-expressions/#built-in-functions)), so writing your own is practice. Compare them:

**Absolute value as a procedure and as a function** (StepCode)

```stepcode
Program AbsoluteValues
    Define x, result As Integer;
    Write "Type a whole number: ";
    Read x;
    // A procedure call is a statement on its own line
    ShowAbsolute(x);
    // A function call is a value you can store or use
    result <- Absolute(x);
    Write "The function returned ", result;
    Write "Twice the absolute value is ", Absolute(x) * 2;
EndProgram

// Procedure: does a job (writes), gives nothing back
Procedure ShowAbsolute(x As Integer)
    If x < 0 Then
        Write "The procedure says ", -x;
    Else
        Write "The procedure says ", x;
    EndIf
EndProcedure

// Function: computes a value and gives it back
Function Absolute(x As Integer): Integer
    If x < 0 Then
        Return -x;
    EndIf
    Return x;
EndFunction
```

When you type `-42`, you should see:

```text
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:

```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)`, `n` is a formal parameter.
- **Actual parameters**, also called **arguments**, are the real values in the call. In `ShowTable(n + 1)`, the argument is the value of `n + 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`, `Real` and `String`.
- **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 `ByRef` after the type.

*Figure: Press Next step to run both calls side by side. By value, p is a copy, so n keeps 5. By reference, n and p are two names for one box, so n ends at 6.*

This program from the course wiki starts with `n` equal to 5 and calls two procedures that add 1:

**Passing by value and by reference** (StepCode)

```stepcode
Program ValueAndReference
    Define n As Integer;
    n <- 5;
    IncrementCopy(n);
    Write "Back in the program, n is ", n;
    IncrementOriginal(n);
    Write "Back in the program, n is ", n;
EndProgram

// By value: p is a copy of the argument
Procedure IncrementCopy(p As Integer)
    p <- p + 1;
    Write "Inside IncrementCopy, p is ", p;
EndProcedure

// By reference: p is another name for the argument
Procedure IncrementOriginal(p As Integer ByRef)
    p <- p + 1;
    Write "Inside IncrementOriginal, p is ", p;
EndProcedure
```

You should see:

```text
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](/blog/programming-fundamentals-variables-and-data-types/#5-swap-two-variables), is the classic case:

**Swap two variables by reference** (StepCode)

```stepcode
Program SwapValues
    Define a, b As Integer;
    Write "Type A: ";
    Read a;
    Write "Type B: ";
    Read b;
    Swap(a, b);
    Write "A is now ", a;
    Write "B is now ", b;
EndProgram

// Exchanges the values of two variables
Procedure Swap(x As Integer ByRef, y As Integer ByRef)
    Define temp As Integer;
    temp <- x;
    x <- y;
    y <- temp;
EndProcedure
```

When you type `3` and then `8`, you should see:

```text
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](/blog/programming-fundamentals-final-project/#1-slide-one-row) 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.

*Figure: A call puts a new frame on top, and Return removes it. While Average runs, its own total hides the program's total, which keeps 100 the whole time.*

**Shadowing a variable** (StepCode)

```stepcode
Program Shadowing
    Define total As Integer;
    total <- 100;
    Write "Average of 4 and 8: ", Average(4, 8);
    Write "total in the program is still ", total;
EndProgram

Function Average(a As Integer, b As Integer): Real
    // This total is local: it only exists inside Average
    Define total As Integer;
    total <- a + b;
    Return total / 2;
EndFunction
```

You should see:

```text
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](/blog/programming-fundamentals-arrays/#how-an-array-works), 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.

**Array toolkit, part 1: read and print** (StepCode)

```stepcode
Program ArrayToolkit
    Define numbers As Integer;
    Dimension numbers[10];
    Define count As Integer;
    count <- ReadArray(numbers);
    WriteNoNewline "The array is: ";
    PrintArray(numbers, count);
EndProgram

// Gives back the smaller of two numbers
Function Smaller(a As Integer, b As Integer): Integer
    If a > b Then
        Return b;
    EndIf
    Return a;
EndFunction

// Reads up to 10 numbers into the array and gives back how many it read
Function ReadArray(list As Integer[]): Integer
    Define count, i As Integer;
    Write "How many numbers (max 10)? ";
    Read count;
    count <- Smaller(count, 10);
    For i <- 1 To count Step 1 Do
        Read list[i];
    EndFor
    Return count;
EndFunction

// Writes the first count numbers on one line
Procedure PrintArray(list As Integer[], count As Integer)
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        WriteNoNewline list[i], " ";
    EndFor
    Write "";
EndProcedure
```

When you type `5`, then `4`, `1`, `5`, `3` and `2`, you should see:

```text
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.

**Array toolkit, part 2: sum, biggest and smallest** (StepCode)

```stepcode
Program ArrayToolkit
    Define numbers As Integer;
    Dimension numbers[10];
    Define count As Integer;
    count <- ReadArray(numbers);
    WriteNoNewline "The array is: ";
    PrintArray(numbers, count);
    Write "The sum is: ", Sum(numbers, count);
    Write "The biggest is: ", Biggest(numbers, count);
    Write "The smallest is: ", Smallest(numbers, count);
EndProgram

// Gives back the smaller of two numbers
Function Smaller(a As Integer, b As Integer): Integer
    If a > b Then
        Return b;
    EndIf
    Return a;
EndFunction

// Reads up to 10 numbers into the array and gives back how many it read
Function ReadArray(list As Integer[]): Integer
    Define count, i As Integer;
    Write "How many numbers (max 10)? ";
    Read count;
    count <- Smaller(count, 10);
    For i <- 1 To count Step 1 Do
        Read list[i];
    EndFor
    Return count;
EndFunction

// Writes the first count numbers on one line
Procedure PrintArray(list As Integer[], count As Integer)
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        WriteNoNewline list[i], " ";
    EndFor
    Write "";
EndProcedure

// Adds every number in the array
Function Sum(list As Integer[], count As Integer): Integer
    Define i, total As Integer;
    total <- 0;
    For i <- 1 To count Step 1 Do
        total <- total + list[i];
    EndFor
    Return total;
EndFunction

// Gives back the biggest number in the array
Function Biggest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] > best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction

// Gives back the smallest number in the array
Function Smallest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] < best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction
```

With the same inputs, you should see:

```text
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.

**Array toolkit, part 3: search** (StepCode)

```stepcode
Program ArrayToolkit
    Define numbers As Integer;
    Dimension numbers[10];
    Define count, wanted As Integer;
    count <- ReadArray(numbers);
    WriteNoNewline "The array is: ";
    PrintArray(numbers, count);
    Write "The sum is: ", Sum(numbers, count);
    Write "The biggest is: ", Biggest(numbers, count);
    Write "The smallest is: ", Smallest(numbers, count);
    Write "Number to search: ";
    Read wanted;
    Write "Its position is: ", Search(numbers, count, wanted);
EndProgram

// Gives back the smaller of two numbers
Function Smaller(a As Integer, b As Integer): Integer
    If a > b Then
        Return b;
    EndIf
    Return a;
EndFunction

// Reads up to 10 numbers into the array and gives back how many it read
Function ReadArray(list As Integer[]): Integer
    Define count, i As Integer;
    Write "How many numbers (max 10)? ";
    Read count;
    count <- Smaller(count, 10);
    For i <- 1 To count Step 1 Do
        Read list[i];
    EndFor
    Return count;
EndFunction

// Writes the first count numbers on one line
Procedure PrintArray(list As Integer[], count As Integer)
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        WriteNoNewline list[i], " ";
    EndFor
    Write "";
EndProcedure

// Adds every number in the array
Function Sum(list As Integer[], count As Integer): Integer
    Define i, total As Integer;
    total <- 0;
    For i <- 1 To count Step 1 Do
        total <- total + list[i];
    EndFor
    Return total;
EndFunction

// Gives back the biggest number in the array
Function Biggest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] > best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction

// Gives back the smallest number in the array
Function Smallest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] < best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction

// Gives back the position of x in the array, or -1 if it is not there
Function Search(list As Integer[], count As Integer, x As Integer): Integer
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        If list[i] = x Then
            Return i;
        EndIf
    EndFor
    Return -1;
EndFunction
```

With the same inputs and `5` as the number to search, you should see:

```text
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](/blog/programming-fundamentals-arrays/), and it calls `Swap` to exchange two neighbors. One subprogram calling another is normal. It is how big programs are built.

**Array toolkit, part 4: reverse and sort** (StepCode)

```stepcode
Program ArrayToolkit
    Define numbers, reversed As Integer;
    Dimension numbers[10], reversed[10];
    Define count, wanted As Integer;
    count <- ReadArray(numbers);
    WriteNoNewline "The array is: ";
    PrintArray(numbers, count);
    Write "The sum is: ", Sum(numbers, count);
    Write "The biggest is: ", Biggest(numbers, count);
    Write "The smallest is: ", Smallest(numbers, count);
    Reverse(numbers, reversed, count);
    WriteNoNewline "Reversed: ";
    PrintArray(reversed, count);
    Sort(numbers, count);
    WriteNoNewline "Sorted: ";
    PrintArray(numbers, count);
    Write "Number to search: ";
    Read wanted;
    Write "Its position is: ", Search(numbers, count, wanted);
EndProgram

// Gives back the smaller of two numbers
Function Smaller(a As Integer, b As Integer): Integer
    If a > b Then
        Return b;
    EndIf
    Return a;
EndFunction

// Reads up to 10 numbers into the array and gives back how many it read
Function ReadArray(list As Integer[]): Integer
    Define count, i As Integer;
    Write "How many numbers (max 10)? ";
    Read count;
    count <- Smaller(count, 10);
    For i <- 1 To count Step 1 Do
        Read list[i];
    EndFor
    Return count;
EndFunction

// Writes the first count numbers on one line
Procedure PrintArray(list As Integer[], count As Integer)
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        WriteNoNewline list[i], " ";
    EndFor
    Write "";
EndProcedure

// Adds every number in the array
Function Sum(list As Integer[], count As Integer): Integer
    Define i, total As Integer;
    total <- 0;
    For i <- 1 To count Step 1 Do
        total <- total + list[i];
    EndFor
    Return total;
EndFunction

// Gives back the biggest number in the array
Function Biggest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] > best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction

// Gives back the smallest number in the array
Function Smallest(list As Integer[], count As Integer): Integer
    Define i, best As Integer;
    best <- list[1];
    For i <- 2 To count Step 1 Do
        If list[i] < best Then
            best <- list[i];
        EndIf
    EndFor
    Return best;
EndFunction

// Gives back the position of x in the array, or -1 if it is not there
Function Search(list As Integer[], count As Integer, x As Integer): Integer
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        If list[i] = x Then
            Return i;
        EndIf
    EndFor
    Return -1;
EndFunction

// Exchanges the values of two variables
Procedure Swap(x As Integer ByRef, y As Integer ByRef)
    Define temp As Integer;
    temp <- x;
    x <- y;
    y <- temp;
EndProcedure

// Copies the array into target in reverse order
Procedure Reverse(source As Integer[], target As Integer[], count As Integer)
    Define i As Integer;
    For i <- 1 To count Step 1 Do
        target[count - i + 1] <- source[i];
    EndFor
EndProcedure

// Sorts the array from smallest to biggest (bubble sort)
Procedure Sort(list As Integer[], count As Integer)
    Define i, j As Integer;
    For i <- 1 To count - 1 Step 1 Do
        For j <- 1 To count - i Step 1 Do
            If list[j] > list[j + 1] Then
                Swap(list[j], list[j + 1]);
            EndIf
        EndFor
    EndFor
EndProcedure
```

With the same inputs and `5` as the number to search, you should see:

```text
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.

**Exercise: functions with confusing names** (StepCode)

```stepcode
Program ConfusingNames
    Write Add(10, 20) + Add(5, 4) - Subtract(7, 3) + 40 + 10 * Add(2, 5);
    Write Subtract(Subtract(Subtract(1, 2), Add(1, 2)), Subtract(Subtract(1, 2), Add(1, 2)));
    Write Subtract(1, 0) * Subtract(1, 1) * Subtract(1, Subtract(1, 1));
    Write Both(Add(Subtract(1, 2), 5) > 6, True);
EndProgram

// The names lie on purpose. Read the bodies!
Function Add(a As Integer, b As Integer): Integer
    Return a - b;
EndFunction

Function Subtract(a As Integer, b As Integer): Integer
    Return a + b;
EndFunction

Function Both(a As Boolean, b As Boolean): Boolean
    Return a Or b;
EndFunction
```

You should see:

```text
-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](/blog/programming-fundamentals-strings/#3-reverse-a-string-with-a-loop).

<details>
<summary>Solution</summary>

**Solution: mirror text** (StepCode)

```stepcode
Program MirrorText
    Define phrase As String;
    Write "Type a text: ";
    Read phrase;
    Write Mirror(phrase);
EndProgram

// Gives back the text followed by its reverse
Function Mirror(phrase As String): String
    Define reversed As String;
    Define i As Integer;
    reversed <- "";
    For i <- 1 To Length(phrase) Step 1 Do
        reversed <- phrase[i] + reversed;
    EndFor
    Return phrase + reversed;
EndFunction
```

When you type `Hello how are you`, you should see:

```text
Type a text: 
Hello how are youuoy era woh olleH
```

</details>

### Exercise 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.

<details>
<summary>Solution</summary>

**Solution: change a date format** (StepCode)

```stepcode
Program DateFormat
    Define date As String;
    Write "Type a date as yyyy/mm/dd: ";
    Read date;
    Write ToDayFirst(date);
EndProgram

// Turns "yyyy/mm/dd" into "dd/mm/yyyy"
Function ToDayFirst(date As String): String
    Define year, month, day As String;
    year <- Substring(date, 1, 4);
    month <- Substring(date, 6, 7);
    day <- Substring(date, 9, 10);
    Return day + "/" + month + "/" + year;
EndFunction
```

When you type `1998/12/10`, you should see:

```text
Type a date as yyyy/mm/dd: 
10/12/1998
```

</details>

### Exercise 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`.

<details>
<summary>Solution</summary>

**Solution: min max normalization** (StepCode)

```stepcode
Program Normalize
    Define values As Real;
    Dimension values[5];
    Define i As Integer;
    For i <- 1 To 5 Step 1 Do
        Read values[i];
    EndFor
    MinMax(values);
    For i <- 1 To 5 Step 1 Do
        WriteNoNewline values[i], " ";
    EndFor
    Write "";
EndProgram

// Rescales the 5 values so the smallest is 0 and the biggest is 1
Procedure MinMax(values As Real[])
    Define low, high As Real;
    Define i As Integer;
    low <- values[1];
    high <- values[1];
    For i <- 2 To 5 Step 1 Do
        If values[i] < low Then
            low <- values[i];
        EndIf
        If values[i] > high Then
            high <- values[i];
        EndIf
    EndFor
    For i <- 1 To 5 Step 1 Do
        values[i] <- (values[i] - low) / (high - low);
    EndFor
EndProcedure
```

When you type `1`, `2`, `5`, `3` and `4`, you should see:

```text
0 0.25 1 0.5 0.75 
```

</details>

## 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. `ByRef` sends 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](/blog/programming-fundamentals-files/), you save data to text files and read it back, so your programs can remember.

- Review [Arrays](/blog/programming-fundamentals-arrays/) if passing arrays felt new.
- Open [StepCode](/projects/stepcode/), the editor I built for my students at UCAB, and turn one of your old programs into subprograms.
