next up previous
Next: 19. Subroutines Up: VisualBasic Previous: 17. PictureBoxes


18. Functions

Sometimes a particular piece of code may be needed in several parts of a program. Rather than write it out every time it is needed, it is convenient to write it in a special part of the program and refer to it when needed. Consider the case above (see Sec.[*]) where the solution of the quadratic equation (i.e. $x=(-b\pm\sqrt{b^2-4ac})/2a$) is required at several points in the program. It is convenient to place this in a "function" as in the following:

' Calculates the solution of the quadratic equation

x = QuadSoln(a,b,c)
.
.
.
y = QuadSoln(d,e,f)
.
.
.
z = QuadSoln(g,h,i)
.
.
.


Function QuadSoln (a, b, c) As Double

QuadSoln = ( -b + Sqr(b^2 - 4*a*c) ) / (2*a)

End Function

As you can see the program calculates the solution of three quadratic equations. Each solution is handled by the same piece of code: QuadSoln. This is called a Function. Note that the Function must be defined as a particular variable type (in this case it is a Double or real number). Note also that the Function actually takes a value - so in this case it can be used inside a mathematical equation. We say that a Function returns a value to the calling programme.

Here is an example programme using a Function to find the minimum of two numbers.

A Function is a separate, self-contained piece of code which can be called, or refered to by another part of the program, and which returns a value to the calling part of the program. They are very useful when the same piece of code is used many times.


next up previous
Next: 19. Subroutines Up: VisualBasic Previous: 17. PictureBoxes
Chris Allton 2006-10-27