# Lesson 17 Creating a Function

### 17.1 Creating User-Defined Functions

A function is similar to a sub procedure,  both are called by the main procedure to fulfil certain tasks. However, there is one difference, a function returns a value whilst a sub procedure does not. It merely performs a certain job. There are two types of functions, the built-in functions, and the user-defined functions.

To create a user-defined-function in Visual Basic 2013, you can type the function procedure directly into the code window as follows:

```Public Function functionName (Argument As dataType,..........) As dataType
```
or
`Private Function functionName (Argument As dataType,..........) As dataType`

*The keyword Public indicates that the function is applicable to the whole project and the keyword Private indicates that the function is only applicable to a certain module or procedure. An argument is a parameter that can pass a value back to the function. You can include as many arguments as you can.

#### Example 17.1: BMI Calculator

This BMI calculator is a Visual Basic 2013 program that can calculate the body mass index or BMI of a person based on the body weight in kilogram and the body height in meter. BMI can be calculated using the formula weight/( height )2, where weight is measured in kg and height in meter. If you only know your weight and height in lb and feet, then you need to convert them to the metric system. If your BMI is more than 30, you are considered obese. You can refer to the following range of BMI values for your weight status.

• Underweight = <18.5
• Normal weight = 18.5-24.9
• Overweight = 25-29.9
• Obesity = BMI of 30 or greater

#### The Code

```Public Class Form1
Private Function BMI(Height As Single, weight As Single) As Double
BMI = weight / Height ^ 2
End Function

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
Dim h As Single, w As Single
h = Val(TextBox1.Text)
w = Val(TextBox2.Text)
LblBMI.Text = BMI(h, w)
End Sub
End Class
```