Functions
Back to Main Page
In the last exericise you used a procedure called AddVAT - the procedure changed the variable Price in your main program.

Functions are similar to procedures, but more versatile. Like procedures you pass a
parameter to them.
Unlike procedures, functions can return a
new value that is calculated inside the function's code.

Algorithm:

- The user enters 2 numbers
- The function Max is
called
- The function calculates which is the biggest number of the two
- The user is told which number is the biggest

We're going to write the function called Max.
The function will compare 2 numbers sent to it as parameters, First and Second, to see which is biggest


Task 1

Type in the following code:
From the Tools menu, select Add Procedure

Make sure that
function and public are selected

Name your function
Max

Now complete the function by typing in the following code:
Run your program to test that it works correctly



How did the function work? Let's look at it step by step.


We have input two numbers called
First and Second


The function is called during the line below, in the highlighted section:

Form1.Print "The largest number is " &
Max (First, Second)


When VB sees the code Max(First, Second), it calls the function Max and passes the variables First and Second as parameters to this function.

The function Max then does its work and calculates which number is biggest and
passes this value back to the main program as Max

The value is then displayed on the form with an appropriate message.




Task 2

Write a program which reads in a number typed in by the user and doubles this number. The program should then display the result with an appropriate message on the screen.
You should write and use a function named Doubleit for this exercise.



End of Tasks
Hosted by www.Geocities.ws

1