Lesson 5.3

Functions and Return

Watch: Functions and Return - p5.js tutorial

Video for 5.3:

When functions like ellipse() are executed the result is an action on the canvas - a drawing. Other functions like draw() do not result in such an action, but return a value, usually a number.

In this lesson we will learn how to write this second type of function.

Start with a simple example. Imagine we wanted a program to find the number of cm in a given number of inches. There are 2.54 cm per inch. We would write

To see the result, we could call the function with a call to print() in setup().

Take another example. Imagine we wanted a program to find the number of meters in a given number of centimeters. There are 100 cm per meter, so we could write

We can combine these functions to find the number of meters in a given number of inches.

The function first finds the number of cm in the number of inches given, and then passes that result to the function for finding meters from centimeters. We can see the output for this function by writing a test function.

We calculate the results that we should obtain if our function is working properly. This calculation should not use the function we have written since we are trying to test its validity. The four tests shown are somewhat arbitrary. Try to vary the examples to catch possible errors, especially at boundary conditions.

The results can be seen in the console.

Exercise 5.3a: Use the conversion factors below to develop a function to convert miles to inches. Reuse functions as much as possible. View the result by calling a test function in setup().

The result called in setup() .

Here is a test function.

and here the console output.

Exercise 5.3b: Write a program that finds the area of a circle. View the result by calling a test function in setup().

Exercise 5.3c: Write a program that finds the area of a ring. View the result by calling a test function in setup().

The first parameter is the outer radius, r1, and the second the inner radius, r2.

Exercise 5.3d: : Write a program that finds the surface area of a pipe. View the result by calling a test function in setup().

The first parameter is the length of the pipe, h, the second the outer radius, R, and the third the inner radius, r.