[go: up one dir, main page]

0% found this document useful (0 votes)
14 views9 pages

Cit2457 VB Unit 3

Uploaded by

animelab186
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views9 pages

Cit2457 VB Unit 3

Uploaded by

animelab186
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

UNIT 3

PROCEDURE
Visual Basic offers different types of procedures to execute small sections of coding in
applications. The various procedures are elucidated in details in this section. Visual Basic
programs can be broken into smaller logical components called Procedures. Procedures are
useful for condensing repeated operations such as the frequently used calculations, text and
control manipulation etc. The benefits of using procedures in programming are:
 It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.
 Procedures used in one program can act as building blocks for other programs with slight
modifications.
A Procedure can be Sub, Function or Property Procedure.

Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the
procedure is called, the statements between Sub and End Sub are executed. The syntax for a sub
procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures namely general procedures and event
procedures.

Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
Private Sub Form_Load()
....statement block..
End Sub
Event Procedures acquire the declarations as Private by default.

General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure.
In order to add General procedure:
 The Code window is opened for the module to which
the procedure is to be added.
 The Add Procedure option is chosen from the Tools
menu, which opens an Add Procedure dialog box as
shown in the figure given below.
 The name of the procedure is typed in the Name
textbox
 Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.
 Under Scope, Public is selected to create a procedure that can be invoked outside the
module, or Private to create a procedure that can be invoked only from within the
module.
We can also create a new procedure in the current module by typing Sub ProcedureName,
Function ProcedureName, or Property ProcedureName in the Code window. A Function
procedure returns a value and a Sub Procedure does not return a value.

Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are
especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks
complete within the function. The following function procedure calculates the third side or
hypotenuse of a right triangle, where A and B are the other two sides. It takes two arguments A
and B (of data type Double) and finally returns the results.

Function Hypotenuse (A As Double, B As Double) As Double


Hypotenuse = sqr (A^2 + B^2)
End Function

The above function procedure is written in the general declarations section of the Code window.
A
function can also be written by selecting the Add Procedure dialog box from the Tools menu and
by choosing the required scope and type.

Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties for Forms, Standard modules and Class modules. Visual Basic provides three
kind of property procedures-Property Let procedure that sets the value of a property, Property
Get procedure that returns the value of a property, and Property Set procedure that sets the
references to an object.

Built – in - Functions

The mathematical functions are very useful and important in programming because very often
we need to deal with mathematical concepts in programming such as chance and probability,
variables, mathematical logics, calculations, coordinates, time intervals and etc.
The common mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp, Log, Sin,
Cos, Tan , Atn, Fix and Round.

(i) Rnd is very useful when we deal with the concept of chance
and probability. The Rnd function returns a random value
between 0 and 1.
Example 1:
Dim num as integer
Private Sub Command1_Click ( )
Num=Int(Rnd*6)+1
Label1.Caption=Num
End Sub
Now, run the program and then click on the roll die button, you will get an output like the figure
below:

Numeric Functions
The numeric functions are Int, Sqr, Abs, Exp, Fix, Round and Log.
a) Int is the function that converts a number into an integer by truncating its decimal part and the
resulting integer is the largest integer that is smaller than the number. For example, Int(2.4)=2,
Int(4.8)=4, Int(-4.6)= -5, Int(0.032)=0 and so on.

b) Sqr is the function that computes the square root of a number. For example, Sqr(4)=2,
Sqr(9)=2 and etc.

c) Abs is the function that returns the absolute value of a number. So Abs(-8) = 8 and Abs(8)= 8.

d) Exp of a number x is the value of ex. For example, Exp(1)=e1 = 2.7182818284590

e) Fix and Int are the same if the number is a positive number as both truncate the decimal part
of the number and return an integer. However, when the number is negative, it will return the
smallest integer that is larger than the number. For example, Fix(-6.34)= -6 while Int(-6.34)=-7.

f) Round is the function that rounds up a number to a certain number of decimal places. The
Format is Round (n, m) which means to round a number n to m decimal places. For example,
Round (7.2567, 2) =7.26

g) Log is the function that returns the natural Logarithm of a number. For example,
Log 10= 2.302585

String Functions
The string function are Len, Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase, Instr, Val,
Str ,Chr and Asc.

(i)The Len Function


The length function returns an integer value which is the length of a phrase or a sentence,
including the empty spaces. The format is
Len (“Phrase”)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22

(ii) The Right Function


The Right function extracts the right portion of a phrase. The format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phrase where the portion of the phrase is
going to be extracted. For example,
Right(“Visual Basic”, 4) = asic

(iii)The Left Function


The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example,
Left (“Visual Basic”, 4) = Visu

(iv) The Ltrim Function


The Ltrim function trims the empty spaces of the left portion of the phrase. The format is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”, 4)= Visual basic

(v) The Rtrim Function


The Rtrim function trims the empty spaces of the right portion of the phrase. The format is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic ”, 4) = Visual basic

(vi) The Trim function


The Ttrim function trims the empty spaces on both side of the phrase. The format is
Trim(“Phrase”)
.For example,
Trim (“ Visual Basic ”) = Visual basic

(viii) The Mid Function


The Mid function extracts a substring from the original phrase or string. It takes the following
format:
Mid(phrase, position, n)
Where position is the starting position of the phrase from which the extraction process will start
and n is the number of characters to be extracted. For example,
Mid(“Visual Basic”, 3, 6) = ual Bas

(ix) The InStr function


The InStr function looks for a phrase that is embedded within the original phrase and returns
the starting position of the embedded phrase. The format is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded phrase. For
example
Instr(1, “Visual Basic”,” Basic”)=8
(x) The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters. On the other hand,
the Lcase function converts all the characters of a string to small letters. For example,
Ucase(“Visual Basic”) =VISUAL BASiC
Lcase(“Visual Basic”) =visual basic

(xi) The Str and Val functions


The Str is the function that converts a number to a string while the Val function converts a
string to a number. The two functions are important when we need to perform mathematical
operations.

(xii) The Chr and the Asc functions


The Chr function returns the string that corresponds to an ASCII code while the Asc function
converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for
“American Standard Code for Information Interchange”. Altogether there are 255 ASCII codes
and as many ASCII characters. Some of the characters may not be displayed as they may
represent some actions such as the pressing of a key or produce a beep sound. The format of the
Chr function is
Chr(charcode)
and the format of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38

Control Structures
Control Statements are used to control the flow of program's execution. Visual Basic supports
control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as
Do While...Loop, While...Wend, For...Next etc.

1. If...Then selection structure


The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If

2. If...Then...Else selection structure


The If...Then...Else selection structure allows the programmer to specify that a different action is
to be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

3. Nested If...Then...Else selection structure


Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1 Method 2
If < condition 1 > Then If < condition 1 > Then
statements statements
ElseIf < condition 2 > Then Else
statements If < condition 2 > Then
Else statements
Statements Else
End If If < condition 3 > Then
statements
eg: If average > 75 Then Else
txtGrade.Text = "A" Statements
ElseIf average > 65 Then End If
txtGrade.Text = "B" End If
ElseIf average > 55 Then EndIf
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If

4. Select...Case selection structure


Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single
block of statements from among multiple blocks of statements. Select...case is more convenient
to use than the If...Else...End If. .

Syntax of the Select...Case selection structure


Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

LOOPS
Visual Basic allows a procedure to be repeated as many times as the processor can support. This
is generally called looping. Looping is known as a repetitive structure. (an action is to be
repeated until given condition is true).
There are several formats for a do loop

Do While... Loop Statement


The Do While...Loop is used to execute statements until a certain condition is met.

General Syntax
Do While <contidion>
Statements
Increment
Loop

eg:
Dim number As Integer
number = 1
Do While number <= 100
number = number + 1
Loop
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is
tested; if condition is True, then the statements are executed. When it gets to the Loop it goes
back to the Do and tests condition again. If condition is False on the first pass, the statements
are never executed

Do...Loop While Statement


The Do...Loop While statement first executes the statements and then test the condition after
each execution. The following program block illustrates the structure:
General Syntax
Do
Statements
Increment
Loop While <contidion>

eg: Dim number As Long


number = 0
Do
number = number + 1
Loop While number < 201
The programs executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 201. If so, the program again executes the
statements between Do and Loop While else exits the Loop.

Do Until...Loop Statement
Unlike the Do While...Loop structures, the Do Until... Loop structure tests a condition for falsity.
Statements in the body of a Do Until...Loop are executed repeatedly as long as the loop-
continuation test evaluates to False.

Syntax
Do Until <condition>
Statements
Increment
Loop

eg:
Dim number As Long
number=0
Do Until number > 1000
number = number + 1
Print number
Loop

The For...Next Loop


The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition
structure handles all the details of counter-controlled repetition.

Syntax
For <variable> = st.value to end_value step <step_value>
Statement
Next

eg: The following loop counts the numbers from 1 to 100:


Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next

Exit For and Exit Do


A For...Next loop condition can be terminated by an Exit For statement. Consider the following
statement block.

Dim x As Integer
For x = 1 To 10
Print x
If x = 5 Then
Print "The program exited at x=5"
End If
Next

The Following statement blocks containing Do...While loop is terminated using Exit Do
statement.

Dim x As Integer
Do While x < 10
Print x
x=x+1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If
Loop

You might also like