Home

Procedural Programming


Please note that any code on this page is pseudocode, meaning it won't work in any actual programming language.

Functions

The first idea we need to explore is that of a function, which is sometimes called a method, subroutine, or procedure when used in a CS (Computer Science) context. A function is a mapping between inputs and outputs; it is a set of instructions which dictate what should be done to a set of inputs to create the corresponding set of outputs.

In math, you've likely encountered functions which take in a single input and return a single output; some commonly recognized examples would be trigonometric or logarithmic functions: sin(x), cos(x), ln(x), etc. We can also define our own functions using function notation, like this: f(x) = x^2, g(x) = 2x - 3, h(x) = 3sin(2πx).

Similarly, in CS we can define our own functions which accept data in the form of variables, called parameters. We can then use statements and control structures to dictate what should be done to the parameters to obtain our output values, known as return values. Some languages restrict functions to only have one return value, while in others we can have an arbitrary amount of return values. We can then use these defined functions elsewhere in our code.

The main benefit of using functions while programming is that you can write code to perform some task once, and then reuse it an indefinite amount of times.

A Simple Example

FUNCTION addSeven(inputNumber):
{
  outputNumber = inputNumber + 7;
  return outputNumber
}

In the example above, the function keyword tells the computer that the following code block is the body of a function. Right after the keyword is the name of the function, addSeven, and in parenthesis the parameters which the function will accept; in this case, there is only one: inputNumber. The body of the function contains two statements, the first of which assigns the value of the expression inputNumber + 7 to the variable outputNumber. The second statement starts with the return keyword, which basically alerts the computer that whatever expression follows it should be the returned value (should be the output).

In fact, we could actually shorten this code even further by combining the two statements in the body into a single statement:

FUNCTION addSeven(inputNumber):
{
  return inputNumber + 7
}

What we've done is eliminated the middleman. Because the return keyword signals that the entire expression to its right should be returned, we can remove the outputNumber variable and simply put its value as the expression to be returned.

Now that we have a nice, clean example function defined, let's use it! Because our function deals with numeric datatypes, it makes the most sense to use it in an expression, so let's try to evaluate 15 - addSeven(2).

The first step will be evaluating the term addSeven(2), which is known as a function call. In a function call, we pass a value (or a variable, which represents a value) to the function, and the function returns an output value based on what value was sent to it. In this case, the function takes the input number, adds seven, and then returns it, so if the input is 2, the output will be 9. Hence the whole expression will evaluate to 15 - 9 = 6.

Another Example

FUNCTION sum(num1, num2):
{
  outputNumber = num1 + num2
  return outputNumber
}

Here we have a function, called sum, which accepts two parameters, num1 and num2. Notice that when we have multiple parameters, they are notated as a comma-separated list. The function assigns the sum of those two parameters to the variable outputNumber, and then returns that value. As before, we can eliminate the middleman to change the function to this:

FUNCTION sum(num1, num2):
{
  return num1 + num2
}

Now, let's try it in an expression: sum(5, 6) * sum(2, -5). This evaluates to 11 * -3 = -33. Pretty simple. Let's get a little spicy: sum(addSeven(2), addSeven(-5)). Here, we have the function from the first example, addSeven(), inside our sum() function, as an argument. One thing you'll notice is that when talking about functions, we normally write the function name followed by and open and closed parenthesis. To evaluate this, we'll first evaluate the addSeven() function calls, and then the sum() function. sum(addSeven(2), addSeven(-5)) = sum(9, 2) = 11

A Challenging Example

On the control structures page, we learned how to use a loop to sum up the values in an array. Let's try to do the same thing, but wrap it in a function, so that we can sum up any array we want, as many times as we want.

FUNCTION sumArray(array):
{
  int i = 0;
  int sum = 0;
  WHILE i < ?:
  {
    sum = sum + array[i];
    i = i + 1;
  }
  return sum;
}

You'll notice that we used our function keyword to alert the computer that the block of code will be a function. The function is named sumArray and accepts one parameter, array. Inside the function we declare two variables, i and sum, and assign them to 0. Then, we have a while loop, inside of which we add the next array value (array[i]) to the running tally sum, and then increase the value of i by one for the next loop iteration. Finally, once the loop is done, we will return the value of the sum variable.

However, you'll notice that we've run into a little snag in our while conditional. The problem is that previously, we knew that we had five elements in our array, so the array values went from 0 to 4. However, right now, we don't know exactly how many values the input array will have; if we put in an arbitrary number - say, 5 - we will end up with an IndexOutOfBoundsError if our actual input has a different number of elements.

This conveniently gives me an opportunity to talk about built-in functions. These functions are provided by some languages and they allow us to get information such as the number of elements in the array. This is very helpful, because to traverse a general array, we need our i to vary from 0 to the length of the array minus 1. For now, we're going to assume that our programming language has a length() function built in, which tells us the length of an array. Depending on the language the name of the function and how to use it varies slightly, but again, the concept is the important part here. Let's try rewriting our function using our length() built-in function:

FUNCTION sumArray(array):
{
  int i = 0;
  int sum = 0;
  WHILE i < length(array):
  {
    sum = sum + array[i];
    i = i + 1;
  }
  return sum;
}

Our while loop's condition now limits the values of i to go from 0 to one less than the length of the array. Arrays are 0-indexed, so the indicies go from 0 to the length of the array minus one. Therefore, our i value now exactly corresponds with the indicies of the array, which means the loop will traverse the array successfully, with no IndexOutOfBoundsError.

Now that we've defined our function, let's use it:

arrayOfIntegers = [1, 2, 3, 4, 5];
int sum = 0;
sum = sumArray(arrayOfIntegers);

When we run this code, the variable arrayOfIntegers refers to the list of numbers from 1 to 5. Next, the int type variable sum is initialized to 0 (we say a variable is initialized to some value if we declare it and assign it to that value at the same time). The last line will set sum to whatever value is to the right of the assignment operator. In this case, that value is whatever is returned by the sumArray() function when we pass in arrayOfIntegers as the argument, which will be the sum of the numbers 1 to 5, or 15.

Because we used the length() function, our function sumArray() is very flexible and can be used with arrays of all sizes, because to traverse any array, i must range from 0 to the length of the array minus one. Writing your programs with flexibility and maintainability in mind is known as soft-coding, while code which is hard to maintain and generally very unflexible is known as hard-coded. To see this difference a little more starkly, here's two examples of our while loop from a while back:

int i = 0;
int sum = 0;
array = [1, 2, 3, 4, 5]
WHILE i < 5:
{
  sum = sum + array[i];
  i = i + 1;
}
int i = 0;
int sum = 0;
array = [1, 2, 3, 4, 5]
WHILE i < length(array):
{
  sum = sum + array[i];
  i = i + 1;
}

The first example is hard-coded because it is unflexible: if we change the number of values in array without changing the while conditional, the code will break. However, in the second example, the while loop is soft-coded because no matter how many values we put in array the code will still perform its intended purpose: summing the values. The chief hallmark of a hard-coded piece of software is the placement of seemingly arbitrary values, like the 5 in the while conditional, rather than flexible solutions like the length() function.

Libraries

Libraries (sometimes known as modules), are packages of open-source (free to use) software which provide useful functions/procedures which you can use in your own code. Libraries are normally developed around a common theme, like providing advanced mathematical or statistical analysis functions or making GUI (Guided User Interface) creation easier. This is super helpful when programming, because it means that you don't have to write your whole program from the ground up. Additionally, since library authors wrote the entire suite of functionality for a specific purpose, it is normally super optimized and efficient, and doesn't require you to learn the ins and outs of whatever particular algorithm they're implementing. Some examples of popular Python libraries include: manim, pygame, or numpy. If they look intimidating right now, take a deep breath and don't worry. We'll get there.

In Conclusion

Functions take inputs and return the corresponding outputs, which is useful because it allows us to reuse our code multiple times; for example, we can wrap a useful behavior, like summing an array, in a function. Additionally, we can use functions other people have written by importing libraries into our code, which is done in different ways in different languages. As you become more knowledgeable about programming, the types of parameters and return values you deal with will broaden, and the types of things you do in the function body will become more advanced and diverse, but the general concept of functions is always the same.

Now that you know about the functions, it's time to learn about OOP (Object Oriented Programming).


Home    Back to Top