Monday, August 17, 2020

Procedures in Visual Basic:

Procedures in Visual Basic:

Procedure is a sequence of statements executed as a unit.  Procedure normally simplifies programming by breaking the program into smaller logic components. Procedures are useful for condense repeating or sharing the task.

Benefits of programming with procedure

  1. The repetition of the code is avoided.
  2. If program size is reduced, which consume less memory and result in faster program execution?
  3. Maintenance of program (applying changes) become is   easier.
  4. The debugging of the program( pressing and eliminating errors) also become easier
  5. The program become easy to understand

Types of procedure

  1.  General procedure
  2.  Event procedure

General procedure: A sub procedure is a block of code which is not associated with an event and is to be explicitly called. By breaking the code into sub procedures, it becomes easier to find or modify the code in your application.

Event procedure: In an event procedure the code gets automatically trigger when an object in Visual Basic recognizes that any event has occurred like a click or a double click.  The name of the procedure established and association between the object and the code, event procedure is attach to forms and controls

All event procedures used the same general syntax.

Private sub  controlname_ eventname( arguments)

            Statements

End sub

Creating a General procedure

You can create general procedures in two ways.  One way by manually going to the general declaration section and typing through to the menu

To create a new general procedure manually type a procedure heading in the code window and press enter. The procedure heading can be as simple as sub or function followed by name

e.g. 

Sub Show()

Function Fact()

When you press enter Visual Basic responds by completing the template for the procedure.

Sub show()

End sub

Function Fact()

End  Function

Then you can type code to complete procedure

Sub Show()

Msgbox “hello”

End Sub

Creating a General procedure through the menu:

To add a procedure with the help of menu from the tool menu to display the following add procedure dialogue box.

Creating General Procedure

Type the name of the procedure in the name box; select the type of procedure and scope of the click ok button.

This would automatically enter the sub and end sub statements within the declaration section with the specified name

Calling a procedure

There are two ways to call a sub procedure:

Both this statement call a sub named add,

Call Show()

Or

Show()

The procedure accepting the arguments:

Arguments can be passed to the procedure which is to be mentioned in the pair of parentheses following the procedure name.

The values for the procedure or to be passed while calling the particular procedure.


Public Sub Add( a as integer, b  as integer)

Dim c as integer

 c= a + b

Msgbox “ The sum of two arguments =”&c

End sub


Private sub command1_click ()

Dim num1,num2 as integer

num1 = Inputbox(“ Enter the first number”)

num2 = Inputbox(“ Enter the Second number”)

call Add( num1 num2)

End sub

Argument ByValue and ByRef

By default Visual Basic procedure accept the argument by reference.  The user can also pass argument by Value using ByVal keyword before the argument name.

Public Sub Add( a is integer)

End Sub

The procedure Add() accepts the augment of type integer by reference.  To pass an argument by value to the procedure

Private Sub Add( ByVal a as integer)

End sub

Difference between passing and argument By Value and By Reference:

By Value

 By Reference

A separate copy of that variable is passed as an argument

A reference of a variable is pass to the procedure

The variable value in the calling and the called procedure is stored at separate location

The variable value in the calling and the called procedure is stored at same location

Any changes made in the called procedure are not updated in calling procedure

Any changes made in called procedure are updated in the calling procedure

Consumption of memory space is more

Consumption of memory space is less


The optional arguments:

When a procedure is called then it is must to pass the list of arguments it is going to accept.

e,g The add procedure is designed to accept two integer as the augments and if it is called as

Call  add(10)

Or 

Call add()

It will result in an error.  The argument can be made as an optional argument by preceding its declaration with the keyword optional.  If the value is not pass for an optional argument then it will not result in an error.

Public Sub Add(a As Integer, Optional b As Integer)

MsgBox "Sum of two numbers is" & a + b

End Sub

Providing the default value for the optional argument:

If the value is not passed to the optional argument then its value is assumed to be zero.  If some default value is to be assigned to the function then the default value can be mentioned in the following format.

Public sub pro_name(arg_name1 as data_type, Optional arg_name2 as data_type=default _value)

Public Sub Add(a As Integer, Optional b As Integer=20)

MsgBox "Sum of two numbers is" & a + b

End Sub

Private sub Command1_click()

Call add(10)

End sub

If the value is not passed to the second argument then it will consider the default value for the optional argument b. 

The scope of the Procedure:

The scope of the procedure may be declared either as a private or public. If the scope of the procedure is declared as a private then that particular procedure can be called from the same form

If the scope of the procedure is declared as a public it can be called from the same form as well as from the different forms. 

Add one more forms to the project

PROJECT-> ADD FORM

If the following procedure is written in form2 and its scope is declared as public then it can be called from form 1 as well as form 2.

Public  Sub  Add( a as integer,  b as integer)

Dim c as Integer

Msgbox “The sum of two numberis”&c

End sub

Executing procedure on Different Form

To call the add procedure present on form2 from the code in form1. Write the following code in the code window of the form.

Private Sub Command1_Click()

Call Form2.Add(10,20)

End Sub


Wednesday, August 12, 2020

Array & Its Type

Arrays:

An array is defined as a group of elements of similar type. A variable can store one value at a time in it, but a single array can store multiple values at same time

The individual element of an array can be referred using an index which begins with 0

There might be an instance where you may need to store probably names of 10 students of 10 numbers in which case declaring 10 different variables would not be very practical. In such situations you can make use of arrays.

Advantages of arrays:


  1. All the array elements shares the same name
  2. Large amount can be handled in easy way as the individual elements of an array can be referred using an index which begins with zero
  3. Array elements are stored in a consecutive memory location

 

Declaration of an array:

Syntax

Dim variable name [{[subscript]}] as Data Types

Subscript: You need to specify the lower and the upper bounds for the subscript [lower to upper]

You can declare an array using a dim statement, followed by the name of the subscript value in parenthesis.

Types of arrays:

 The arrays two types in Visual Basic

1.  Fixed Size Arrays

2.  Variable Size Arrays

Fixed Size Arrays:- 

Fixed size array which all will always remain the same size and its size cannot be change at runtime.

Declaring fixed size arrays

Dim array name (upper _limit) as data type

 Or

Dim array name (lower limit to upper limit) as data type

Lower limit:- lower limit is  optional in a fixed size array, if not specified considered to be zero.

Upper limit:- the upper bound cannot exceed the range of long data type.

Example:

Dim marks(1 to 15) as integer

To specify only upper limit give this declaration

Dim marks(15) add integer


Option Base 1 statement

Default lower limit of an array is 0, if you want to make default lower limit to 1 for all the array in your form you can use following statement in general declarations

Option Base 1

Program to demonstrate the use of an array:

Private sub command1_click()

Dim num(5), i as integer

Dim sum As long

For i = 1 to 5

num(i)=Inputbox(“Enter the numbers”)

sum=sum+num(i)

Next i

Msgbox “Sum of given number is” &sum 

Msgbox “Average of given five number is” &sum/5

End sub

 

Dynamic Arrays:

The size of the dynamic array can be changed at run time of. You declare the array as a dynamic by giving it an empty dimension list. ReDim statements can be used to assign the size of the dynamic array. 

Syntax

Dim  array_name()

The actual number of element with ReDim statement

ReDim array_name()

The size of the dynamic array can be changed much time during the execution of program

Private sub command1_click()

Dim num() , i, sum ,x As  integer

x= input box(“ How many numbers you want”)

ReDim num(x)

For i = 1 to x

num(i)=Inputbox(“Enter the numbers”)

sum=sum+num(i)

Next i

Msgbox “sum of given number is” &sum 

Msgbox “Average of given five number is” &sum/5

End sub

Preserve Keyword:-

Sometimes users may want to change the size of the array without losing the data into the array. You can do this by using ReDim with the preserve keyword.

The preserve statements can be used to preserve the element of the dynamic array even if the array size is changed.

Syntax

ReDim preserve array_name (new_size) 

Private Sub Command1_click()

Dim num()  as integer, i as integer

ReDim num(5)

For i = 1 to x

num(i)=i*10

Next i

Msgbox “sum of given number is” &sum 

Msgbox “Average of given five number is” &sum/5

ReDim preserve num(10)

For i = 6 to 10

num(i)=i*100

Next i

For i = 1 to 10

Print num(i)

Next i

End sub

Output:

10 20 30 40 50 600 700 800 900 1000

If preserve statement is not used along with RiDim statement the result would have been 

 0 0 0 0 0 600 700 800 900 1000

Advantages of dynamic arrays:

  1.  Size of Array need not be  declare in advance
  2.  The size of an array is set at runtime using the ReDim statement
  3.  The size of an array can be changed many times during execution of program
  4.  The previous value of an array can be retained using the preserve statement along with the ReDim statement.

Stacks & Stack Terminologies:

Stacks & Stack Terminologies:

A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stack.  This means, in particular, that the elements are removed from the stack in the reverse order of that in which they were inserted into a stack.


Special terminology used for two basic operations associated with stack:

  1. Push:  is the term used to insert an element into a stack.
  2. Pop:  is the term used to delete an element from a stack.


Array representation of Stacks:

Stack may be represented in the computer memory in various ways. Usually by means of one way list or a linear array. Stack will be maintained by linear array STACK. A pointer variable TOP, which contain the location of the top element of stack. And a variable MAXSTK which gives the maximum number of elements that can be held by the stack. The condition TOP= 0 or TOP=NULL will indicate the stack is empty.


Figure shows the array representation of stack. Since top = 3, the stack has three elements, XXX, YYY and ZZZ; and since MAXSTK=8, there is a room for five more elements in stack.

The operation of adding an element on to a stack and the operation of removing an element from the stack may be implemented, respectively, by the following procedure called push and pop.

In executing the procedure push, one must first check whether there is a room in the stack for the new item; if not, then we have the condition known as overflow.  Analogously, in executing the procedure pop, one must first test whether there is an element in the stack to be deleted; if not then we have the condition known as underflow.

Algorithm: PUSH (STACK, TOP, MAXSTK, ITEM)

This procedure Push an item onto a stack.

1.    [Stack already filled?]

If TOP= MAXSTK, then: print: OVERFLOW, and Return. 

2.    Set TOP:=TOP+1 [Increase TOP by 1]

3.    Set Stack [TOP]:=ITEM [Insert ITEM in new TOP position.]

4.    Return

Algorithm: POP (STACK, TOP, ITEM)

     This procedure Delete an item from a stack.

1.    [Stack has an item to be removed?]

If TOP= 0, then: print: UNDERFLOW, and Return. 

2.    Set ITEM :=STACK [TOP]  [Assign TOP element to ITEM.]

3.    Set Top: TOP-1. [Decrease TOP by 1.]

4.. Return


Polish notation:

In most common arithmetic operations, the operator symbol is placed between its two operand. 

For example, 

 A+B, C-D,    E*F,    G/H

This is called as infix notation.

Polish notation refers to the notation in which the operator symbol is placed before it's two operands also called as prefix notations.

For example, 

                                    +AB,   -CD,    *EF,    /GH

Translate following in this expression into polish (prefix) notation:

  1. (A+B)*C=[+AB]*C=*+ABC
  2. A+(B*C)=A+[*BC]= +A*BC
  3. (A+B)/(C-D)=[+AB]/[-CD]=/+AB-CD

Reverse polish notation (postfix notation) refers to the analogous notation in which the operator symbol is place after two operand.

For example, 

                                    AB+,   CD+,   EF+,    GH+

Evaluation of Postfix Expression:

 

Suppose P is an arithmetic expression written in postfix notation.  The following algorithm, which uses a stack to hold the operands, evaluates P. 

Algorithm:  This algorithm finds the value of an arithmetic expression P written in postfix notation.

    1. Add a right parentheses “)” at end of P. [This acts as a sentinel]
    2. Scan P from left to right and repeat step 3 and 4 for each element of P until the sentinel is encountered.
    3. If an operand is encountered, put it on STACK.
    4. If an operator is encounter, then:

a)    Remove the top two element of stack, where A is the top element and B is the next top element.

b)    Evaluate  B X A

c)    Place the result of (b) back on STACK

        [End of if structure]

    5. Set VALUE equals to the top element on STACK

              6. Exit

Consider the following arithmetic expression P written in postfix notation:

                     P:        5,         6,         2,         +,         *,          12,       4,         /,          -

 Equivalent infix expression of Q follows:

                     Q: 5*(6+2)-12/4

 We evaluate P by simulating the above algorithm.  First we add a sentinel right parenthesis at the end of P to obtain

              P:        5,         6,         2,         +,         *,          12,       4,         /,          -

(1)       (2)       (3)       (4)       (5)           (6)       (7)       (8)       (9)

The elements of P have been labelled from left to right for easy reference.  Following figure shows the content of stack as each element of P is scanned, the final number in the stack is ,37,  which is assigned to the value when the sentinel “)” is scanned, is the value of P.