• UNIT 5: ARRAYS, FUNCTIONS AND PROCEDURES IN VISUAL BASIC

    Key Unit Competency: Use array, functions and procedures in Visual Basic program.

    Learning objectives:

    •Identify the importance of using array in the program

    •Identify the role of using each category of the function in the program

    •Give the syntax and step to write a function

    •Differentiate Inbuilt function from user-defined function and their usage

    •Design and write a Visual Basic program using an array

    •Design and write a Visual Basic Program using a user defined and in-built functions

    Introductory activity

    In one family, a mother has a culture of storing daily expenses for each day of the year; every day she records daily expenses which means 365 times per year.

    Answer the following questions:

    1. What do you think about 365 times of records per year in terms of programming data storage?

    2. What could be the best way of doing it much better?

    3. Design a VB interface which can allow her to input date/day, Expense designation, Amount, Submit, Update, Delete and Search buttons.

    4. Write a VB program using a functions and procedures which receives marks 35 students in S5 Computer Science and Mathematics where by marks in 10 subjects will be entered, the program should calculate and display the average and percentage got by each student and then generates all students whom their performance is above class average.

    Learning activity 5.1.

    Observe and analyze the two tables below and then answer on the following questions:

    Q1. Give the difference between the way data are stored in Table A and Table B

    Q2. Declare variables and keep the data for both Tables

    Q3.Discuss what would happen if you have to records 500 Students Names? Is it a challenge? If yes discuss what could be the best solution?

    An array is a list of variables with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item.

    By using an array, you can refer a list of values by the same name, and use a number that’s called an index or subscript to identify an individual element based on its position in the array. The indexes of an array range from zero to a number one less than the total number of elements in the array. When you use Visual Basic syntax to define the size of an array, you specify its highest index, not the total number of elements in the array.

    a. Dimension of an Array

    An array can be one dimensional or multidimensional. One dimensional array is like a list of items or a table that consists of one row of items or one column of items.

    Example: If we need to record one hundred names, it is difficulty to declare 100 different names; this is a waste of time and efforts. So, instead of declaring one hundred different variables, we need to declare only one array. We differentiate each item in the array by using subscript, the index value of each item, for example name(1), name(2),name(3) .......etc. , makes declaring variables more streamline.

    A two dimensional array is a table of items that made of rows and columns. The format for a one dimensional array is ArrayName(x), the format for a two dimensional array is ArrayName(x,y) and a three dimensional array is ArrayName(x,y,z) .

    Example: A two dimensional array can be considered as a table, which will have x number of rows and y number of columns. Normally it is sufficient to use one dimensional and two dimensional arrays, you only need to use higher dimensional arrays if you need to deal with more complex problems.

    b.Declaring Arrays

    We can use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declares an array that could be used only in a local procedure.

    b.1. The general format to declare a one dimensional array

    Dim arrayName(subs) as dataType where subs indicates the last subscript in the array.

    Example

    Dim StudName(5) as String

    The above statement will declare an array that consists of 5 elements starting from

    StudName (1) to StudName (5).

    Application activity 5.1

    1. Differentiate a one dimensional array from a two dimensional array

    2. Declare both one dimensional and two dimensional arrays which can keep 100

    5.1.2. Arrays initialization and accessing elements of an array

    Learning activity 5.2.

    1. Write a VB program that initializes your First name, Last name, age, combination and level of studies

    2. Having an array Num already initialized with 10 numbers calculate the sum of the first and last element.

    3. Discuss the way you think elements of an array can be accessed?

    When creating an array, each item of the series is referred to as a member of the array. Once the array variable has been declared, each one of its members is initialized with a 0 value. Most, if not all of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array. To initialize an array, you can access each one of its members and assign it a desired but appropriate value.

    In mathematics, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A VB array is zero-based which means that the first member of the series has an index of 0, the second has an index of 1. In math, the series would be represented as X0, X1, X2, X3, and X4. In VB, the index of a member of an array is written in its own parentheses. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value or array initialization. Below are some examples:

    a. General syntax of array initializationa.

    1. One dimensional array initialization


    b. Accessing elements of an array

    Once an array has been initialized, that is, once it holds the necessary values, you can access and use these values. The main technique used to use an array consists of accessing each member or the necessary member based on its index. Remember that an array is zero-based.

    You can access the first member using an index of 0. The second member has an index of 1, and so on. Here are some examples: print function or list box can be used to access elements of an array.

    Note: The two ways for accessing elements of an array are not excessive.

    Syntax:

    1. [Print][variableName] or

    2. [ListName.AddItem] [VariableName]

    You can give an example like this: Suppose an array declared as Dim Marks(4) As Double

    a. With one dimensional array

    Program example 1

    Program example 2

    b.With two dimensional array

    Program example 1

    Program example 2

    5.1.3. Entering and displaying arrays elements

    Learning activity 5.3.

    1. Discuss different types of controls and functions that can be used to input and to display elements of an array

    The program accepts data entry through an input box and displays the entries in the form itself. As you can see, this program will only allow a user to enter student’s marks each time a user clicks on the start button.

    a. Entering arrays elements

    Examples

    b.Displaying arrays elements

    An array student Marks has been already initialized, the next step will be to display its elements using a loop.

    .Application activities 5.3.

    1. Write a VB program which allow a user to Input 10 elements of an array and then displays even and odd numbers separately.

    5.2. FUNCTIONS IN VB

    Functions are “self-contained” modules of code that accomplish a specific task. Functions usually “take in” data, process it, and “return” a result. Once a function is written, it can be used over and over and over again. Functions can be “called” from the inside of other functions.

    You can define a function in a module, class, or structure. It is public by default, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it.

    A function can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.

    There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Visual Basic language. There are various mathematical, string or conversion functions.

    5.2. 1 Built-in Functions

    Learning activity 5.4.

    1. Discuss the importance of using functions use in programming context

    The built-in functions are functions which are automatically declared by the compiler, and associated with a built-in function identifier.

    a. MsgBox egg Function

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

    yourMsg = MsgBox(Prompt, Style Value, Title)

    The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table1 for types of command button displayed. The Title argument will display the title of the message board.

    We can use named constant in place of integers for the second argument to make

    the programs more readable. In fact, VB6 will automatically shows up a list of names constant where you can select one of them.

    Example 1: yourMsg=MsgBox( “Click OK to Proceed”, 1, “Startup Menu”) and yourMsg=Msg(“Click OK to Proceed”. vbOkCancel,”Startup Menu”) are the same. Your Msg is a variable that holds values that are returned by the MsgBox egg function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 2 shows the values, the corresponding named constant and buttons.

    Table 2: Return Values and Command Buttons


    The codes for the test button see Figure 4

    Private Sub Test_Click()

    Dim testmsg As Integer


    When the user clicks on the test button, the image like the one shown in Figure 4 will appear. As the user clicks on the OK button, the message “Testing successful” will be displayed and when he/she clicks on the Cancel button, the message “Testing fail” will be displayed.

    a.3. Icon besides the message

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

    Example 3

    You draw the same Interface as in example 2 but modify the codes as follows:

    b.The InputBoxegg Function

    An InputBoxegg function displays a message box where the user can enter a value or a message in the form of text. The format is myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

    myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The arguments are explained as follows:

    •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 users can use it as his intended input or he may change to the message he wish to key in.

    •X-position and y-position: the position or the coordinate of the input box. Below is an example of an input box

    The procedure for the OK button

    When a user click the OK button, the input box as shown in Figure 7 will appear. After user entering the message and click OK, the message will be displayed on the caption, if he/she clicks Cancel, “No message” will be displayed.

    c. String function

    In this lesson, we will learn how to use some of the string manipulation function such as Len, Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase, Instr, Val, Str ,Chr and Asc.

    c. 1 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 above example will produce the output 1, 4, 8. The reason why the last value is 8 is because z# is a double precision number and so it is allocated more memory spaces.

    c. 2 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.

    Example

    Right(“Visual Basic”, 4) = asic

    c. 3 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.

    Example

    Left (“Visual Basic”, 4) = Visu

    c. 4 The Ltrim Function

    The Ltrim function trims the empty spaces of the left portion of the phrase. The format is

    Ltrim(“Phrase”)

    Example

    Ltrim (“Visual Basic”, 4)= Visual basic

    c. 5 The Rtrim Function

    The Rtrim function trims the empty spaces of the right portion of the phrase. The format is

    Rtrim(“Phrase”)

    Example:

    Rtrim (“Visual Basic”, 4) = Visual basic

    c. 6 The Trim function

    The Trim function trims the empty spaces on both side of the phrase. The format is

    Trim(“Phrase”)

    Example

    Trim (“ Visual Basic ”) = Visual basic

    c. 7 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.

    Example

    Mid(“Visual Basic”, 3, 6) = ual Bas

    c. 8 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.

    Example

    Instr(1, “Visual Basic”,” Basic”)=8

    c. 9 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.

    Example

    Ucase(“Visual Basic”) =VISUAL BASICLcase(“Visual Basic”) =visual basic

    c. 10 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.

    c. 11 The Chr and the Asc functions

    The Chr function returns the string that corresponds to an ASCII code while the Ascfunction 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

    d.The mathematical 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.

    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.

    Example

    Round (7.2567, 2) =7.26

    g. Log is the function that returns the natural Logarithm of a number.

    Example

    Log (10)= 2.302585

    h. Sin is the function that returns the natural Sinus of a number.

    Example

    Sin(10)= -0,544021

    i. Tan is the function that returns the natural Tangent of a number.

    For example

    Tan(10)= 0,6403608

    j. Cos is the function that returns the natural Cosinus of a number.

    Example

    Cos(10)= -0,839071

    e. Graphical methods (Line, Circle and Rectangle)

    e. 1 Drawing lines

    The Line method lets you draw lines in Visual Basic 6. You need to specify the starting point and the finishing point of the line in the argument. You may also specify the color of the line. This is optional, though.

    i. A simple line

    The following code example shows how to draw a simple line using the Line method.

                                      

    ii. A line with drawing styles Form’s Draw

    Style property lets you draw lines using a particular style. The constant values of the DrawStyle property are 0 (vbSolid), 1 (vbDash), 2 (vbDot), 3 (vbDashDot, 4 (vbDashDotDot), 5 (vbTransparent) and 6 (vbInsideSolid). The default value is 0, vbSolid. You may use the numeric constant or the symbolic constant such as vbSolid, vbDash etc to change drawing styles in your code.

    NOTE: The Draw Style property does not work if the value of Draw Width is other than 1.

    Example



    e. 2 Drawing circles

    You can draw a circle using the Circle method in Visual Basic 6. You may also use the Circle method to draw different geometric shapes such as ellipses, arcs etc. You need to specify the circle’s center and radius values to draw a circle using the Circle method.

    i. A simple circle

    The following code draws a simple circle using the Circle method in Visual Basic 6.

    Example

    In the above code, (2500, 2500) is the circle’s center, and the radius value is 2000. The color constant ‘vbBlue is an optional argument.

    ii. A circle filled with color

    The following code example shows how to fill a circle with color in Visual Basic 6.

    Example


    e. 3 Rectangle

    The Line method can be used to draw different geometric shapes such as rectangle, triangle etc. The following example shows you how to draw a rectangle using the Line method in Visual Basic 6.

    Example e.3

    f. Format function

    Formatting output is an important part of programming so that the visual interface can be presented clearly to the users. Data in the previous lesson were presented fairly systematically through the use of commas and some of the functions like Int, Fix and Round. However, to better present the output, we can use a number of formatting functions in Visual Basic. The three most common formatting functions in VB are Tab, Space, and Format

    f. 1. The Tab function

    The syntax of a Tab function is Tab No; x

    The item x will be displayed at a position that is n spaces from the left border of the output form. There must be a semicolon in between Tab and the items you intend to display (VB will actually do it for you automatically).

    Example f.1.


    f. 2. The Space function

    The Space function is very closely linked to the Tab function. However, there is a minor difference. While Tab No means the item is placed n spaces from the left border of the screen, the Space function specifies the number of spaces between two consecutive items.

    Example f.2.


    f. 3. The Format function

    The Format function is a very powerful formatting function which can display the numeric values in various forms. There are two types of Format function, one of them is the built-in or predefined format while another one can be defined by the users.

    (a) The syntax of the predefined Format function is

    Format (n, “style argument”) where n is a number and the list of style arguments is given in Table 6.

    Example f.2.


    Application activity 5.4.

    Write a VB program using Input box that accept a string value from the keyboard and then convert it into an integer value, performs and displays its sinus, cosinus and tangent

    5.2.2. User Defined functions

    Learning activity 5.5.

    1. Design the interface bellow and use provided codes Example a, Example b and Example c.

    The functions that we create in a program are known as user defined functions. In this guide, we will learn how to create user defined functions and how to use them in C Programming

    Functions are used because of following reasons:

    a. To improve the readability of code.

    b. Improves the re usability of the code, same function can be used in any program rather than writing the same code from scratch.

    c. Debugging of the code would be easier if you use functions, as errors are easy to be traced.

    d. Reduces the size of the code, duplicate set of statements are replaced by function calls.

    a. Function prototype

    A function prototype is simply the declaration of a function that specifies function’s name, parameters and return type. It doesn’t contain function body. A function prototype gives information to the compiler that the function may later be used in the program.

    Syntax of function prototype in VB

    Function FunctionName(arg1 As type1, arg2 As type2, ...) As return data types

    In the above example public, Function FunctionName(argument1 As type1, argument As type2,...) As return data types

    The function prototype provides the following information to the compiler:

    1. name of the function is FunctionName

    2. return type of the function is Double

    3. two arguments of type (argument1 As type1, argument As type2) have passed to the function

    The function prototype is not needed if the user-defined function is defined before the module program. Public indicates that the function is applicable to the whole project and Private indicates that the function is only applicable to a certain module or procedure.

    Example a

    Public Function FV (PV As Double, i As Double, n As Double) As Double

    c. Function definition

    A function definition specifies the name of the function, the types and number of parameters it expects to receive, and its return type. A function definition also includes a function body with the declarations of its local variables, and the statements that determine what the function does.

    Example b


    In this example, a user can calculate the future value of a certain amount of money he/she has today based on the interest rate and the number of years from now, supposing he/she will invest this amount of money somewhere. The calculation is based on the compound interest rate.

    d.Function calling

    When you call a function you are basically just telling the compiler to execute that function. To call a function “Call” key word can be used or not.

    Syntax

    [procedureName][argumentList]

    Example c


    The following program will automatically compute examination grades based on the marks that a student obtained. The code is shown below:

    e. Passing Arguments by Value and by Reference in Visual Basic

    In Visual Basic, you can pass an argument to a procedure by value or by reference. This is known as the passing mechanism, and it determines whether the procedure can modify the programming element underlying the argument in the calling code.

    The procedure declaration determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword.

    e. 1. Passing Arguments by Value

    You pass an argument by value by specifying the ByVal keyword for the corresponding parameter in the procedure definition. When you use this passing mechanism, Visual Basic copies the value of the underlying programming element into a local variable in the procedure. The procedure code does not have any access to the underlying element in the calling code.

    After executing the above codes output will be: 1

    e. 2. Passing Arguments by Reference

    You pass an argument by reference by specifying the ByRef keyword for the corresponding parameter in the procedure definition. When you use this passing mechanism, Visual Basic gives the procedure a direct reference to the underlying programming element in the calling code.

    Example d.2


    e. 3. Differences between Passing an Argument By Value and By Reference

    When you pass one or more arguments to a procedure, each argument corresponds to an underlying programming element in the calling code. You can pass either the value of this underlying element, or a reference to it. This is known as the passing mechanism.

    Application activities 5.5.

    1. Write a VB function to find the Maximum of three numbers

    2. Write a VB function to sum all the numbers in a list

    Sample List : (8, 2, 3, 0, 7)

    Expected Output : 20

    5.2.3 Procedures

    Learning activities 5.6.

    1. Write a function which allows a user to input monthly salary and then allow him/her to withdraw amount which does not exceed 90% of his/her monthly income otherwise the software should inform the user that the remaining amount (10%) is reserved for the future needs saving .

    A procedure is a block of Visual Basic statements inside Sub, End Sub statements. Procedures do not return values. A procedure, in any language, is a self-contained piece of code which carries out a well-defined piece of processing.

    a. Syntax of a procedure


    b.Types of procedure

    b.1. Event procedures

    Visual Basic has two kinds of procedures, event procedures and general procedures.

    An event procedure is “attached” to an object and is executed when the relevant event impinges on that object.

    e.g., “Click” is an event procedure attached to a button, and is executed when the button is clicked (by the user, with the mouse). Event procedures are named by VB. VB creates a name for an event procedure by concatenating the name of the object and the name of the event, and putting an underscore between them.

    e.g., the click event procedure for a button named “CmdQuit” will be named “CmdQuit_Click”.

    b.2. General procedures

    A general procedure is not attached to an object such as a button or a text field. A general procedure is located in the “general” section of a Form.

    Unlike event procedures, general procedures are only executed when you explicitly call them from your code. You are responsible for naming general procedures, and you can give them any name you like (within normal VB naming rules).

    e.g. suppose there are 10 different places in your program where you might want to issue the following error message (with a beep to attract the user’s attention):

    Note: We use procedures and functions to create modular programs. Visual Basic statements are grouped in a block enclosed by Sub, Function and matching End statements. The difference between the two is that functions return values, procedures do not.

    A procedure and function is a piece of code in a larger program. They perform a specific task. The advantages of using procedures and functions are:

    •Reducing duplication of code

    •Decomposing complex problems into simpler pieces•Improving clarity of the code

    •Reuse of code

    •Information hiding

    Application activities 5.6.

    1. Write a VB program using procedure which helps a business Woman who has a shop in Nyanza city southern province to input manufactured , expiring and buying year for each product that she has in the shop and then informs whether the product has expired or still valid.

    END UNIT ASSESSMENT

    1. What do you understand by an array?

    2. Discuss about the use of arrays in program.

    3. Give the syntax and steps to write a function and a procedure

    4. Differentiate a function from a procedure

    5. Differentiate a built in function from a user defined function and explain the use of each one

    6. Write a VB procedure which solves quadratic equation (ax2+bx+c=0) each output must be underlined using a procedure called underline ().

    7. Design a VB function program to find Factorial of an entered number

    UNIT 4 :SQL AND DATABASE PROJECTUNIT 6 : VISUAL BASICPROJECT