0% found this document useful (0 votes)
9 views

Functions

Uploaded by

a044550a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Functions

Uploaded by

a044550a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

University of Basrah

Collage of Engineering
Department of Petroleum
Computer Programming

Lecture Six
Functions

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6. Functions of Visual Basic


A function is a set of commands code that performs a specific action, where they
are combined under a certain name, and when you call this name has executed
these orders. There are two types of functions, the built-in functions (or internal
functions) and the functions created by the programmers.

6.1 Built-in Functions

Visual Basic offers a rich assortment of built-in functions. The numeric and string
variables are the most common used variables in programming. Therefore, Visual
Basic provides the user with many functions to be used with a variable to perform
certain operations or type conversion. Detailed description of the function in
general will be discussed in the following functions section. The most common
functions for (numeric or string) variable X are stated in the following table.

6.1.1 Mathematical Function

Function Description
Y= Math.Abs(X) Absolute of X, |X|
Y= Math.Sqrt(X) Square root of X , √𝑋
Y= Math.Sign (X) (-1 or 0 or 1) for (X<0 or X=0 or X>0)
Y= Math.Exp (X) ex
Y= Math.Log (X) Natural logarithms, ln𝑋
Y= Math.Log(X)/ Math.Log (10) Log𝑋

Y= Math.Sin (𝑋)
Y= Math.Cos (𝑋) Trigonometric functions
Y= Math.Tan (𝑋)
Y= Math.ASin (𝑋) Inverse Trigonometric functions
Y= Math.ACos (𝑋)
Y= tan−1(𝑋) (Where X angle in radian).
Y= Math.ATan (𝑋)
Y= Int(X) Integer of X
Y= Fix(X) Take the integer part

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-1:
*Private Sub Button1_Click()
Dim num1, num2 As Integer
num1 = Val(TextBox1.Text)
num2 = Math.Abs(num1)
Label1.Text = num2
End Sub
*Private Sub Button2_Click()
Dim num1, num2 As Single
num1 = Val(TextBox2.Text)
num2 = Math.Exp(num1)
Label2.Text = num2
End Sub
*Private Sub Button3_Click()
Dim num1, num2 As Single
num1 = Val(TextBox3.Text)
num2 = Fix(num1)
Label3.Text = num2
End Sub
*Private Sub Button4_Click()
Dim num1, num2 As Single
num1 = Val(TextBox4.Text)
num2 = Math.Log(num1)
Label4.Text = num2
End Sub
*Private Sub Button5_Click()
Dim num1, num2 As Single
num1 = Val(TextBox5.Text)
num2 = Int(num1)
Label5.Text = num2
End Sub

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6.1.2 String Functions


Y=Len(X) Number of characters of Variable
Y=LCase (X) Change to small letters
Y=UCase (X) Change to capital letters
Y=Left (X,L) Take L character from left
Y=Right (X,L) Take L character from right
Y=Mid (X,S,L) Take only characters between S and R

Examples:
Private Sub Button1_Click()
Dim A, B, C, D, M, L, H As String
H= My Name Is
A = LCase(H)
B = UCase(H)
C = Mid(H, 3, 5)
D = LSet(H, 7)
M = RSet(H, 4)
L = Len(A)
TextBox1.Text = A
TextBox2.Text = B
TextBox3.Text = C
TextBox4.Text = D
TextBox5.Text = M
TextBox6.Text = L
End Sub

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-2: Design a visual basic program with two textboxes. One is used to enter
any string and the other is used to display the inverse of this string.
Private Sub Button1_Click()
Dim x As String
Dim i, y As Integer
x = TextBox1.Text
y = Len(x)
For i = y To 1 Step -1
TextBox2.Text &= Mid (x, i, 1)
Next
End Sub

6.1.3 Converting Functions

Visual Basic provides several conversion functions can used to convert values
into a specific data type. The following table describes the convert function.

Function Description
The function CDbl converts, integer, long integer, and single
precision numbers to double-precision numbers. If x is any
CDbl
number, then the value of CDbl(x) is the double-precision number
determined by x.
The function CInt converts long integer, single-precision, and
double precision numbers to integer numbers. If x is any number,
CInt
the value of CInt(x) is the (possibly rounded) integer constant that
x determines.
The function CLng converts integer, single precision and double-
precision numbers to long integer numbers. If x is any number,
CLng
thevalue of CLng(x) is the (possibly rounded) long integer that x
determines.
The function CSng converts integer, long integer, and double-
precision numbers to single-precision numbers. If x is any number,
CSng
the value of CSng(x) is the single-precision number that x
determines.

4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

The function CStr converts integer, long integer, single-precision,


double-precision, and variant numbers to strings. If x is any
CStr number, the value of CStr(x) is the string determined by x. unlike
the Str function, CStr does not place a space in front of positive
numbers.[variant]
The Val function is used to convert string to double-precision
Val
numbers.

6.1.4 MsgBox Function

The objective of MsgBox is to produce a pop-up message box and prompt the user
to click on a command button before he /she can continues. This format is as
follows:

Variable Name=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, displays the message in the message box. The Style
Value determines the type of command buttons appear on the message box, as
shown in Table 10.1. The Title argument will display the title of the message
board.

Table 10.1: Style Values

Style Value Named Constant Buttons Displayed


0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

yourMsg is a variable that holds values that are returned by the MsgBox ( )
function. The type of buttons being clicked by the users determines the values. It
has to be declared as Integer data type in the procedure or in the general
declaration section. Table 10.2 shows the values, the corresponding named
constant and buttons.

Table 10.2: Return Values and Command Buttons

Value Named Constant Named Constant Button Clicked


1 MsgBoxResult.Ok vbOk Ok button
2 MsgBoxResult.Cancel vbCancel Cancel button
3 MsgBoxResult.Abort vbAbort Abort button
4 MsgBoxResult.Retry vbRetry Retry button
5 MsgBoxResult.Ignore vbIgnore Ignore button
6 MsgBoxResult.Yes vbYes Yes button
7 MsgBoxResult.No vbNo No button

Ex 6-3:

Private Sub Button1_Click()


Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

To make the message box looks more sophisticated, you can add an icon besides
the message. There are four types of icons available in VB2010 as shown in Table
10.3

Table 10.3: Named Constants and Icons


Value Named Constant Icon

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-4

Private Sub Button1_Click()


Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test
Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

6.1.5 The InputBox Function

An InputBox function allows the user to enter a value or a message in a text box.

Variable Name =InputBox (Prompt, Title, default_text, x-position, y-position)

8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

userMsg is a variant data type but typically it is declared as string, which


accepts themessage input by the user. The meanings of the arguments:
 Prompt - The message displayed normally as a question asked.

 Title - The title of the Input Box.


• default-text - The default text that appears in the input field where the user
maychange the message according to his or her wish.
 x-position and y-position - the position or the coordinates of the input box.

Ex 6-5:
Private Sub Button1_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter
your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show("userMsg")
Else
MessageBox.Show("No Message")
End If

9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6.2 Creating User-Defined Functions (Sub Procedure and


Function Procedure)
Most computer programs that solve real-world problems are much larger than
those presented in the first few chapters. Experience has shown that the best way
to develop and maintain a large program is to construct it from smaller pieces
each of which is more manageable than the original program. This technique is
called divide and conquer. This chapter describes many key features that facilitate
the design, implementation, operation and maintenance of large programs.

Functions and Subroutines are programs designed for specific task, and could
be called from the main program or from sub-procedures without pre definition
or declaration. Users are allowed to call in any number of times which save the
main program space, since it avoids reputation of code these subroutines could
be designed by user or could be previously built.

function procedures and sub procedures share the same characteristics, with
one important difference- function procedures return a value (i. g., give a value
back) to the caller, whereas sub procedures do not.

6.2.1 declaration syntax

 Function Procedures

Public Function Name (ByVal Variabl1 As datatype) As datatype


Statements
Return Value
End Function

10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Public Function Name (ByVal Variabl1 As datatype, ByVal Variabl2 As


datatype) As datatype
Statements
Return Value
End Function

Call statement

X= Name (Value1)

 Sub Procedures

Public Sub Name (ByVal Variabl1 As datatype)


Statements
End Sub

Public Sub Name (ByVal Variabl1 As datatype, ByVal Variabl2 As datatype)


Statements
End Sub

Call statement

Call Name (Value1, Value2, Value3, ….)

11
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-6: Create a program that calculates the cube root of a number, by using
function.

Public Class Form1


Public Function cubeRoot (ByVal myNumber As Single) As Single
Return myNumber ^ (1 / 3)
End Function
Private Sub Button1_Click()
Label3.Text = cubeRoot(Val(TextBox1.Text))
End Sub
End Class

Ex 6-7: BMI calculator

This BMI calculator is a Visual Basic 2010 program that can calculate the body
mass index of a person based on his or her 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.

12
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

If the BMI is more than 30, a person is 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

Solution
Public Class Form1
Public Function BMI (ByVal height, ByVal weight)
Return (weight) / (height ^ 2)
End Function

Private Sub Button1_Click()


Label4.Text = Format (BMI(TextBox1.Text, TextBox2.Text), "0.00")
End Sub
End Class

13
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-8: Future Value Calculator


In this example, the user can calculate the future value of a certain amount of
money he has today based on the interest rate and the number of years from now,
supposing he or she will invest this amount of money somewhere. The calculation
is based on the compound interest rate. This reflects the time value of money.
Future value is calculated based on the following formula:

The function to calculate the future value involves three parameters namely the
present value (PV), the interest rate (i) and the length of period (n).
Solution

Public Class Form1


Public Function FV (ByVal PV As Single, ByVal i As Single, ByVal n As
Integer) As Double
Return PV * (1 + i / 100) ^ n
End Function

Private Sub Button1_Click()


Label5.Text = FV(TextBox1.Text, TextBox2.Text, TextBox3.Text).ToString
("c")
End Sub
End Class

14
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-9: Write a code program to read three integer numbers. Using a define sub
procedure (Minimum) to determine the smallest of three integers. Display the
smallest value in TextBox.
Solution

Public Class Form1


Sub Minimum (ByVal n1 As Integer, ByVal n2 As Integer, ByVal n3 As
Integer)
Dim min As Integer
n1 = Val(TextBox1.Text)
n2 = Val(TextBox2.Text)
n3 = Val(TextBox3.Text)
min = n1
If n2 < min Then min = n2
If n3 < min Then min = n3
TextBox4.Text = CStr (min)
End Sub

* Private Sub Button1_Click()


Dim n1, n2, n3 As Integer
Minimum (n1, n2, n3)
End Sub
End Class
Or

* Private Sub Button1_Click ()


Minimum (TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub

15

You might also like