0% found this document useful (0 votes)
10 views22 pages

106LT Note2-1

The document is a manual for an Introduction to Programming II course, covering various programming paradigms including procedural, imperative, declarative, logic, functional, and object-oriented programming. It provides detailed explanations of concepts such as classes, methods, inheritance, and data validation, specifically using Visual Basic as the programming language. The manual also includes practical examples and code snippets to illustrate the discussed programming concepts.

Uploaded by

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

106LT Note2-1

The document is a manual for an Introduction to Programming II course, covering various programming paradigms including procedural, imperative, declarative, logic, functional, and object-oriented programming. It provides detailed explanations of concepts such as classes, methods, inheritance, and data validation, specifically using Visual Basic as the programming language. The manual also includes practical examples and code snippets to illustrate the discussed programming concepts.

Uploaded by

saidualiyu7437
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ertyuiopasdfghjklzxcvbnmqwertyu

dfghjklzxcvbnmqwertyuiopasdfgh
vbnmqwertyuiopasdfghjklzxcvbnm
tyuiopasdfghjklzxcvbnmqwertyui
DCS106 MANUAL

INTRODUCTION TO PROGRAMMING II

fghjklzxcvbnmqwertyuiopasdfghjk
bnmqwertyuiopasdfghjklzxcvbnm
yuiopasdfghjklzxcvbnmqwertyuiop
JULY, 2015

hjklzxcvbnmqwertyuiopasdfghjklz
mqwertyuiopasdfghjklzxcvbnmqw
iopasdfghjklzxcvbnmqwertyuiopa
klzxcvbnmqwertyuiopasdfghjklzxc
Prepared By
SALAHUDEEN RIDWAN

qwertyuiopasdfghjklzxcvbnmqwer
pasdfghjklzxcvbnmqwertyuiopasd
xcvbnmrtyuiopasdfghjklzxcvbnmq
yuiopasdfghjklzxcvbnmqwertyuiop
hjklzxcvbnmqwertyuiopasdfghjklz
mqwertyuiopasdfghjklzxcvbnmqw
Table of Contents
Programming Paradigms....................................................................................................................................2
Procedural Programing...................................................................................................................................2
Imperative Programming................................................................................................................................2
Declarative Programming...............................................................................................................................3
Logic Programming.........................................................................................................................................3
Functional Programming................................................................................................................................3
Object-Oriented Programming.......................................................................................................................3
Classes................................................................................................................................................................ 4
Constructors.......................................................................................................................................................6
Data Validation...................................................................................................................................................7
Inheritance.........................................................................................................................................................8
Methods Overriding...........................................................................................................................................9
Polymorphism.....................................................................................................................................................9
Overloading......................................................................................................................................................10
Methods Overloading...................................................................................................................................10
Constructor Overloading..............................................................................................................................11
Array................................................................................................................................................................. 12
Declaring an Array........................................................................................................................................12
The Length Property.....................................................................................................................................12
Two Dimensional Array.................................................................................................................................12
Passing an Array as an Argument to a Procedure or Function......................................................................13
Introduction GUI Applications and Event-Driven Programming.......................................................................14
Event Handling..............................................................................................................................................16

1
Programming Paradigms
A programming paradigm is a fundamental style of computer programming. Programming paradigms differ
in:

- The concepts and abstractions used to represent the elements of a program (such as objects,
functions, variables, constraints, etc.).
- The steps that compose a computation (assignation, evaluation, data flow, control flow, etc.)
Some languages are designed to support one particular paradigm, example:

- Smalltalk supports object-oriented programming


- Haskell supports functional programming
Other programming languages support multiple paradigms’ example:

- C++, C#, Visual Basic, Java and F#


The design goal of multi-paradigm languages is to allow programmers to use the best tool for a job,
admitting that no one paradigm solves all problems in the easiest or most efficient way.

Procedural Programing
This category of programming specifies the steps the program must take to reach the desired state.
Procedures are also known as routines, subroutines, methods, or functions that contain a series of
computational steps to be carried out. Any given procedure might be called at any point during a program's
execution, including by other procedures or itself.

Possible benefits:

• Often a better choice than simple sequential or unstructured programming in many


situations which involve moderate complexity or require significant ease of maintainability.
• The ability to re-use the same code at different places in the program without copying it.
• An easier way to keep track of program flow than a collection of "GOTO" or "JUMP"
statements (which can turn a large, complicated program into spaghetti code).

• The ability to be strongly modular or structured.

• The main benefit of procedural programming over first- and second-generation languages is
that it allows for modularity (grouping), which is generally desirable, especially in large,
complicated programs.

• It prevents a procedure from accessing the variables of other procedures (and vice-versa),
including previous instances of itself such as in recursion.

• Examples are: FORTRAN, COBOL, ALGOL, BASIC and C

Imperative Programming
This is a programming paradigm that describes computation in terms of statements that change a program
state. Imperative programs define sequences of commands for the computer to perform. Imperative
paradigm is synonymous with procedural programming.

2
Declarative Programming
This is a general programming paradigm in which programs express the logic of a computation without
describing its control flow. Declarative programs describe what the computation should accomplish, rather
than how it should accomplish it. Contrary to imperative programming, where a program is a series of steps
and state changes describing how the computation is achieved. Common declarative languages include those
of database query languages (e.g., SQL, XQuery), regular expressions, logic programming, functional
programming, and configuration management systems.

Logic Programming
The logic programming paradigm views computation as automated reasoning over a collection of knowledge.
Facts about the problem domain are expressed as logic formulae, and programs are executed by applying
inference rules over them until an answer to the problem is found, or the collection of formulae is proved
inconsistent. In all of these languages, rules are written in the form of clauses:

H :- B1, …, Bn.

and are read declaratively as logical implications:

H if B1 and … and Bn.

H is called the head of the rule and B1, …, Bn is called the body. Facts are rules that have no body, and are
written in the simplified form:

H.

Major logic programming language families include Prolog, Answer set programming (ASP) and Datalog.

Functional Programming
Functional programming is a programming paradigm that treats computation as the evaluation of
mathematical functions and avoids state changes and mutable data. It emphasizes the application of
functions, in contrast to the imperative programming style, which emphasizes changes in state.

Functional programming is a subset of declarative programming. Programs written using this paradigm use
functions, blocks of code intended to behave like mathematical functions. Functional languages discourage
changes in the value of variables through assignment, making a great deal of use of recursion instead.
prominent functional programming languages are LISP, Scheme, Clojure, Racket, Haskell, F# in
Microsoft .NET and XSLT (XML).

Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm that represents the concept of "objects"
that have data fields (attributes that describe the object) and associated procedures known as methods.
Objects, which are usually instances of classes, are used to interact with one another to design applications
and computer programs. C++, Smalltalk, Java, C#, Perl, Python, Ruby and PHP are examples of object-
oriented programming languages.

Create an analogy of real world object-class scenario (class as a blueprint and object as implementation of
blueprint).

3
Classes
Classes are important in object-oriented programming because they allow you to group related items as a
unit, as well as control their visibility and accessibility to other procedures. Mostly classes contain

Visual Basic is a powerful object-oriented language. An object is an entity that exists in the computer's
memory while the program is running. An object contains data and has the ability to perform operations on
its data. An object's data is commonly referred to as the object's fields, and the operations that the object
performs are the object's methods.

In addition to the many objects that are provided by Visual Basic, you can create objects of your own design.
The first step is to write a class. A class is like a blueprint. It is a declaration that specifies the methods for a
particular type of object. When the program needs an object of that type, it creates an instance of the class.
(An object is an instance of a class.)

The general format of a class declaration in Visual Basic:

Public Class ClassName

Field declarations and method definitions go here…

End Class

In Visual Basic, a class declaration is stored in its own file, and the file is part of the project in which you want
to use it. To create a class in an existing Visual Basic project, click Project on the Visual Basic menu bar, and
then click Add Class…

You will then see the Add New Item window, Notice the Name box at the bottom of the Add New Item
window. This is where you type the name of the file that will contain the class declaration. The filename
should be the same as the name of the class, followed by the .vb extension. For example, if you want to

4
create a class named Customer, you would use the filename [Link]. When you click the Add button, a
file will appear in the code editor, with the first and last line of the class declaration already written for you.

Public Class GradeBook


‘creating method (DisplayMessage()) inside class
Public Sub DisplayMessage()
[Link](“Welcome to Grade Book!”)
End Sub
End Class

The code above is the Visual Basic version of the GradeBook class. The method DisplayMessage() (lines 3-5)
declaration begins with the keyword public to indicate that the method is “available to the public” that is, it
can be called from outside the class declaration’s body by method of other classes or modules. Keyword Sub
indicates that this method will perform a task but will not return any information to its calling method when
it completes its task.

A visual basic project that contains only class GradeBook is not an application that can be executed because
GradeBook does not contain Main. If you try to compile such a project, you will get the error message:

‘Sub Main’was not found in ‘[Link]’

To fix this problem, either we must declare a separate class or module that contains Main, or we must place
Main in class GradeBook. We use a separate module (GradeBookTest in this example) containing Main to
test our class GradeBook.

5
Module GradeBookTest
Sub main()
‘creating object of class GradeBook as gradeBook
Dim gradebook as New GradeBook()

‘calling method of class GradeBook via object (gradebook) of the class


[Link]()
End Sub
End Module

The GradeBookTest module declaration above contains the main method (line 2-8) that control our
application’s execution.

In this application, we would like to call class GradeBook’s DisplayMessage() method to display the welcome
message in the console window. Typically, you cannot call a method that belongs to another class until you
create an object of that class. We begin by declaring variable gradeBook (line 4). Note that the variable’s
type is GradeBook. Each new class you create becomes a new type in Visual Basic that can be used to declare
variables and create objects.

We can now use object gradeBook to call method DisplayMessage(). Line 7 calls DisplayMessage using
variable gradeBook followed by a dot separator (.), the method name DisplayMessage and an empty set of
parentheses. This call causes the DisplayMessage method to perform its task.

Declaring a Method with a Parameter


Parameter: is a variable declared at the header (inside the parentheses) of a method (subroutine or
function), it is a local variable to the method.

Argument: is a variable, constant or expression pass to parameter during call to a method. Notice that the
data type of the variable, constant or evaluated expression of the argument should typically match the data
type defined for the corresponding parameter, or must be convertible to the parameter type.

The next example declares class GradeBook with a DisplayMessage method that displays the course name as
part of the welcome message. The new DisplayMessage method requires a parameter that represents the
course name to output.

Public Class GradeBook


Public Sub DiplayMessage(ByVal courseName As String)
[Link]("Welcome to the grade book for " & vbCrLf & courseName)
End Sub
End Class
Our method DiplayMessage in the above class has parameter with string data type, therefore to call
DiplayMessage method of class GradeBook, we must pass course name to the parameter
courseName which will be concatenated with the string “Welcome to the grade book for”

Module GradeBookTest

Sub Main()
Dim gradeBook As New GradeBook()
[Link]("Please enter the course name")
Dim nameofCourse As String = [Link]()
[Link]()

6
[Link](nameofCourse)
End Sub

End Module

Note that empty parentheses are used in the object-creation expression (New GradeBook() line 4 of
GradeBookTest Module), because no arguments need to be passed to create a GradeBook object.
Line 5 of GradeBookTest prompts the user to enter a course name. Line 6 reads the name from the
user and assigns it to the nameOfCourse variable. The user types the course name and presses
Enter to submit the course name to the program.

Line 9 calls gradeBook’s DisplayMessage method. The nameOfCourse (argument) in parentheses is


passed to method DisplayMessage so that it can perform its task. The value of variable
nameOfCourse in Main becomes the value of method DisplayMessage’s parameter courseName
(parameter) in line 2 of GradeBook class. When you execute this application, you will see that
method DisplayMessage outputs a welcome message with the course name you type.

Instance Variables and Properties (Setters and Getters)


Instance variable is a variable defined in a class (i.e. a member variable), for which each
instantiated object of the class has a separate copy, or instance.

Class variable (Shared Variable, Static Variable) is a variable defined in a class of which a single copy
exists, regardless of how many instances of the class exist.

Setter is a public subroutine (does not return value) declared inside a class with a parameter, it is used to
assign value to instance variable with private access modifier from outside the class.

Getter is a public function (return value) declared inside a class without parameter, it is used to retrieve
value of instance variable with private access modifier from outside the class.

The next version of class GradeBook maintains the course name as instance variable
courseNameValue so that name can be used or modified at any time during an application’s
execution. The variable courseNameValue has an access modifier private indicating that it value
cannot be accessed from outside the class.

Public Class GradeBook


Private courseNameValue As String

Public Function GetCourseName() As String


Return courseNameValue
End Function

Public Sub SetCourseName(ByVal courseNameValue As String)


[Link] = courseNameValue
End Sub

Public Sub DiplayMessage()


[Link]("Welcome to the grade book for " & vbCrLf &
GetCourseName())

7
End Sub
End Class
The class contains three methods, two sub routine (SetCourseName and DisplayMessage) and one
function (GetCourseName).

SetCourseName (Setter method) sub routine accept one parameter and assign it to instance
variable, notice the name of the parameter (courseNameValue) and the instance variable
(courseNameValue), visual basic use the keyword Me to differentiate between local variable and
instance variable. The Me keyword is used to refer to the instance variable

GetCourseName (Getter method) is a function that returns the value stored in the instance variable
courseNameValue. Notice the return type of the function is the same with the return type of the instance
variable.

Method DisplayMessage which specifies no parameters still display a welcome message that includes the
course name. However, the method now uses the GetCourseName function to obtain the course name from
instance variable courseNameValue.

Module GradeBookTest

Sub Main()
Dim gradeBook As New GradeBook()
[Link]("Initial course name is: " & [Link]())

[Link]("Please enter the course name")


Dim theName As String = [Link]()
[Link]()

[Link](theName)
[Link]()
[Link]()

[Link]()
End Sub

End Module

Notice that each of the field declarations (lines 2 through 4) begins with the key word Private. This is an
access specifier that makes the fields private to the class. No code outside the class can directly access
private class fields. Also notice that each of the method headers begin with the Public access specifier. This
makes the methods public, which means that code outside the class can call the methods.

Module Module1

Sub Main()

'Declare a variable that can reference a CellPhone object.


Dim myPhone As CellPhone

'The following statement creates an object using CellPhone class as its


blueprint.
'The myPhone variable will reference the object.

8
myPhone = New CellPhone

'Store values in the object's fields.


[Link]("Nokia")
[Link]("Lumia")
[Link](199.99)

'Display values stored in the fields.


[Link]("The manufacturer of the myPhone is: " &
[Link]())
[Link]("The model number of the myPhone is: " &
[Link]())
[Link]("The retail price of the myPhone is: " &
[Link]())
End Sub

End Module

The statement in line 2 declares a CellPhone variable name myPhone, this is a special type of variable that
can be used to reference a CellPhone object. This statement does not, however, create a CellPhone object in
memory. That is done in line 3. The expression on the right side of the = operator creates a new CellPhone
object in memory, and the = operator assigns the object's memory address to the myPhone variable. As a
result, we say that the myPhone variable references a CellPhone object.

We can then use the myPhone variable to perform operations with the object that it references. This is
demonstrated in line 4, where we use the myPhone variable to call the setManufacturer method. The
"Nokia" string that we pass as an argument is assigned to the object's manufacturer field. Likewise, line 5
uses the myPhone variable to call the setModelNumber method. That causes the string "Lumia" to be
assigned to the object's modelNumber field. And, line 6 uses the myPhone variable to call the setRetailPrice
method. This causes the value 199.99 to be stored in the object's retailPrice field. The statements that
appear in lines 7 through 9 get the values that are stored in the object's fields and displays them on the
screen.

Constructors
A class constructor in Visual Basic is a method named New. (The New method is written in the class as a
Public Sub procedure.) When an instance of a class is created in memory, the New method (the constructor)
is automatically executed. Below is a version of the CellPhone class that has a constructor. The constructor
appears in lines 5 through 9.

Public Class CellPhone


Private manufacturer As String
Private modelNumber As String
Private retailPrice As Double
Public Sub New(ByRef manufact As String, ByVal modNum As String, ByVal retail As
Double)
manufacturer = manufact
modelNumber = modNum
retailPrice = retail
End Sub
Public Sub SetManufacuturer(ByRef manufact As String)
manufacturer = manufact
End Sub
Public Sub SetModelNumber(ByVal modNum As String)

9
modelNumber = modNum
End Sub
Public Sub SetRetailPrice(ByVal retail As Double)
retailPrice = retail
End Sub
Public Function GetManufacturer()
Return manufacturer
End Function
Public Function GetModelNumber()
Return modelNumber
End Function
Public Function GetRetailPrice()
Return retailPrice
End Function
End Class

The program below demonstrates how to create an instance of the class, passing arguments to the
constructor. In line 3, an instance of the CellPhone class is created and the arguments "Samsung", "Core",
and 199.99 are passed to the constructor.

Module Module1

Sub Main()

'Declare a variable that can reference a CellPhone object.


Dim myPhone As CellPhone

'The following statement creates an object using CellPhone class as its


blueprint.
'The myPhone variable will reference the object.
myPhone = New CellPhone("Samsung", "Core", 40000.67)

'Display values stored in the fields.


[Link]("The manufacturer of the myPhone is: " &
[Link]())
[Link]("The model number of the myPhone is: " &
[Link]())
[Link]("The retail price of the myPhone is: " &
[Link]())
End Sub

End Module

Data Validation
Data validation is making sure that all data (whether user input variables, read from file or read from a
database) are valid for their intended data types and stay valid throughout the application that is driving this
data. In essence data validation is about having valid data for a given type of variable.

Inheritance
Inheritance is the ability to define classes that serve as the basis for derived classes. Derived classes inherit,
and can extend, the properties, methods, and events of the base class. Derived classes can also override
inherited methods with new implementations. By default, all classes created with Visual Basic are

10
inheritable. Inheritance lets you write and debug a class one time and then reuse that code as the basis of
new classes.

To inherit from another class, add an Inherits statement with the name of a class you want to use as a base
class as the first statement in your derived class. The Inherits statement must be the first non-comment
statement after the class statement.

Base Class

Public Class Person


Protected name As String
Protected DOB As Date
Public Sub setName(ByVal sName As String)
name = sName
End Sub
Public Sub setAge(ByVal sAge As Date)
DOB = sAge
End Sub
Public Function getName() As String
Return name
End Function
Public Function getAge() As String
Return DOB
End Function
End Class

Derived Class

Public Class Student


Inherits Person
Private regNum As String
Private CGPA As Double
Public Sub setRegNum(ByVal sNum As String)
regNum = sNum
End Sub
Public Sub setCGPA(ByVal sCGPA As String)
CGPA = sCGPA
End Sub
Public Function getRegNum() As String
Return regNum
End Function
Public Function getCGPA() As Double
Return CGPA
End Function
End Class

Test Module

Module Module1

Sub Main()
Dim std As Student
std = New Student
[Link]("Aishah")
[Link]("The name of student is: " & [Link]())
End Sub

End Module

11
Methods Overriding
A derived class inherits the properties and methods defined in its base class. This is useful because you can
reuse these items when appropriate for the derived class. If the property or method in the base class is
marked with the Overridable keyword, you can define a new implementation for the member in the derived
class. Use the Overrides keyword to shadow the member by redefining it in the derived class. This is useful
when you cannot use the member "as it is"

In practice, overridden members are often used to implement polymorphism.

Polymorphism
Polymorphism refers to the ability to define multiple classes with functionally different, yet identically
named methods or properties that can be used interchangeably by client code at run time.

Inheritance also lets you use inheritance-based polymorphism, which is the ability to define classes that can
be used interchangeably by client code at run time, but with functionally different, yet identically named
methods or properties.

Base Class

Public Class Animal


Public Overridable Sub showSpecies()
[Link]("I'm just a regular animal.")
End Sub
Public Overridable Sub makeSound()
[Link]("Grrrrrrrrr")
End Sub
End Class

Derived Class

Public Class Dog


Inherits Animal
Public Overrides Sub showSpecies()
[Link]("I'm a dog.")
End Sub
Public Overrides Sub makeSound()
[Link]("Woof! Woof!")
End Sub
End Class

Derived Class

Public Class Cat


Inherits Animal
Public Overrides Sub showSpecies()
[Link]("I'm a cat.")
End Sub
Public Overrides Sub makeSound()
[Link]("Meow! Meow!")

12
End Sub
End Class

Test Module

Module Module1

Sub Main()
Dim myAnimal As Animal
Dim myDog As Dog
Dim myCat As Cat

myAnimal = New Animal


myDog = New Dog
myCat = New Cat

[Link]("Here is info about an animal.")


showAnimalInfo(myAnimal)
[Link]()

[Link]("Here is info about a dog.")


showAnimalInfo(myDog)
[Link]()

[Link]("Here is info about a cat.")


showAnimalInfo(myCat)
[Link]()
End Sub

Sub showAnimalInfo(ByVal creature As Animal)


[Link]()
[Link]()
End Sub

End Module

Overloading
Overloading is the creation of more than one method or instance constructor in a class with the same name
but different argument types.

Methods Overloading
Overloaded methods have the same name, but accept different number of parameters, or parameters with
different data types.

Public Class TaxClass


Public Function TaxAmount(ByVal decPrice As Decimal, ByVal TaxRate As Single) As
String
TaxAmount = "Price is a Decimal. Tax is $" & (CStr(decPrice * TaxRate))
End Function

Public Function TaxAmount(ByVal strPrice As String, ByVal TaxRate As Single) As


String
TaxAmount = "Price is a String. Tax is $" & CStr((CDec(strPrice) * TaxRate))
End Function
End Class

13
Module Module1

Sub Main()
ShowTax()
End Sub

Sub ShowTax()
Const TaxRate As Single = 0.08

Dim strPrice As String = "64.00"

Dim decPrice As Decimal = 64


Dim tax As New TaxClass

'Call the same method with two different kinds of data.


[Link]([Link](strPrice, TaxRate))

[Link]([Link](decPrice, TaxRate))
End Sub

End Module

Constructor Overloading
Public Class CellPhone
Private manufacturer As String
Private modelNumber As String
Private retailPrice As Double
Public Sub New(ByRef manufact As String, ByVal modNum As String, ByVal retail As
Double)
manufacturer = manufact
modelNumber = modNum
retailPrice = retail
End Sub
Public Sub New(ByRef manufact As String, ByVal modNum As String)
manufacturer = manufact
modelNumber = modNum
End Sub
End Class

Module Module1

Sub Main()
Dim phone1 = New CellPhone("Nokia", "Lumia")
Dim phone2 = New CellPhone("Nokia", "Lumia", 70.89)
End Sub

End Module

Array
Recall the definition of an array as a set of values that are logically related to each other or simply put, an
array is an ordered list of values.

Declaring an Array
14
There are several different correct syntax variations for declaring arrays. The general formats are:

Dim ArrayName(UpperSubscript) As DataType


Dim ArrayName() As DataType = {ListOfValues}
Dim ArrayName As DataType() = {ListOfValues}
Dim ArrayName As DataType() = New DataType (UpperSubscript){}
Examples:
Dim numbers(6) As Integer

Dim numbers() As Integer = {1, 2, 3, 4, 5, 6, 7}

Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7}

The Length Property


Each array in Visual Basic has a property named Length. The value of the Length property is the number of
elements in the array (or the product of the lengths of all its dimensions). For example, consider the array
created by the following statement:
Dim temperatures(24) As Double

The overall size of temperature array is (24 + 1) =25.

Dim prices(3, 4, 5) As Long

The overall size of the array in variable prices is (3 + 1) x (4 + 1) x (5 + 1) = 120.

Two Dimensional Array


A two dimensional array is an array containing another arrays (that is, array of arrays). Example, declaration
of a two-dimensional array with three rows and four columns is:

Dim scores(2, 3) As Double

The numbers 2 and 3 inside the parentheses are the upper subscripts. The number 2 is the subscript of the
last row, and the number 3 is the subscript of the last column. So, the row subscripts for this array are 0, 1,
and 2. The column subscripts are 0, 1, 2, and 3.

When processing the data in a two-dimensional array, each element has two subscripts: one for its row and
another for its column. For example, the following statement stores the number 95 in scores(2, 1):

scores(2, 1) = 95

Programs that process two-dimensional arrays can do so with nested loops. For example, the following code
prompts the user to enter a score, once for each element in the array:

Const MAX_ROW As Integer = 2


Const MAX_COL As Integer = 3
Dim row, col As Integer
Dim scores(MAX_ROW, MAX_COL) As Double
Dim names(MAX_ROW) As String
For row = 0 To MAX_ROW
[Link]("Enter name of student " & (row + 1) & ": ")

15
names(row) = [Link]()
[Link]()
For col = 0 To MAX_COL
[Link]("Enter No. " & (col + 1) & " score: ")
scores(row, col) = CDbl([Link]())
Next
Next

[Link]()
[Link]("Names" & vbTab & "Score1" & vbTab & "Score2" &
vbTab & "Score3" & vbTab & "Score4")

For row = 0 To MAX_ROW


[Link](names(row))
For col = 0 To MAX_COL
[Link](scores(row, col) & vbTab)
Next
[Link]()
Next

Passing an Array as an Argument to a Procedure or Function


Array is passed to a method the same way you pass any other variable. You supply the
array variable name in the appropriate argument when you call the method. When passing an
array as an argument to a procedure or function in Visual Basic, it is not necessary to pass a separate
argument indicating the array's size. This is because arrays in Visual Basic have the Length property that
reports the array's size. The following code shows a procedure that has been written to accept an Integer
array as an argument

Sub ShowArray(ByVal arrayParameter() As Integer)

Dim index As Integer

For index = 0 To [Link] – 1

[Link](array(index))

Next

End Sub

Notice that the parameter variable, arrayParameter, is declared with an empty set of parentheses. This
indicates that the parameter receives an array of any length as an argument. When you call this procedure
you must pass an Integer array as an argument. Assuming that numbers is the name of an Integer array, here
is an example of a procedure call that passes the numbers array as an argument to the ShowArray
procedure:

Dim numbers() As Integer = {1,2,3,4,5,6,7,8,9,10}

ShowArray(numbers)

OOP example

Public Class ArrayTest

16
Private name As String

Public Sub New(ByVal name As String)


[Link] = name
End Sub

Public Function arrayHighest(ByVal arrayParam() As Integer) As Integer


Dim greatest As Integer = arrayParam(0)
For i = 0 To [Link] - 1
If greatest < arrayParam(i) Then
greatest = arrayParam(i)
End If
Next
Return greatest
End Function
End Class

Test Module

Module Module1

Sub Main()
Dim greatestValue As Integer
Dim arrayValues(5) As Integer
Dim arrayObject As New ArrayTest("arrayObject")

For a = 0 To [Link](0)
[Link]("Enter value for index: " & a)
arrayValues(a) = [Link]()
Next

greatestValue = [Link](arrayValues)

[Link]("The highest number entered into the array is: " &
greatestValue)
[Link]()

Dim arrayFixedValues As Integer() = {19, 8, 3}

greatestValue = [Link](arrayFixedValues)

[Link]("The highest number in the fixed array is: " &


greatestValue)
End Sub

End Module

Notice that the arrayHighest function is called twice in Module1 with arrays of different lengths (arrayValues
has length of 6 while arrayFixedValues has length of 3).

Introduction GUI Applications and Event-Driven Programming


In Visual Basic, a GUI application is known as a Windows Forms Application. This is because the windows in
an application's user interface are referred to as forms.

To create a Windows Forms Application project

Step 1: Start Visual Studio.

17
Step 2: On the menu bar, choose File, New, Project. The dialog box should look like this.

Step 3: Click the File menu, and then click New Project. You should see the New Project window shown,
make sure Windows Forms Application is selected as the template, then type the project name then Click the
OK button.

The following diagram shows what you should now see in the Visual Studio interface.

The interface contains three windows: a main window, Solution Explorer, and the Properties window.

If any of these windows are missing, restore the default window layout by, on the menu bar, choosing
Window, Reset Window Layout. You can also display windows by using menu commands. On the menu bar,
choose View, Properties Window or Solution Explorer. If any other windows are open, close them by
choosing the Close (x) button in their upper-right corners.

18
Main window: In this window, you'll do most of your work, such as working with forms and editing code. In
the illustration, the window shows a form in the Form Editor. At the top of the window, the Start Page tab
and the [Link] [Design] tab appear. (In Visual Basic, the tab name ends with .vb instead of .cs.)

Solution Explorer window: In this window, you can view and navigate to all items in your solution. If you
choose a file, the contents of the Properties window changes. If you open a code file (which ends in .vb in
Visual Basic), the code file or a designer for the code file appears. A designer is a visual surface onto which
you can add controls such as buttons and lists. For Visual Studio forms, the designer is called the Windows
Forms Designer.

Properties window: In this window, you can change the properties of items that you choose in the other
windows. For example, if you choose Form1, you can change its title by setting the Text property, and you
can change the background color by setting the Backcolor property.

Toolbox window: This window shows all of the controls that you can place on a form. The controls are
grouped into categories. Example categories are: Common Controls, Containers, Menu & Toolbars, and Data.
Examples of controls are: Button, TextBox, CheckBox, Label, PictureBox, Pointer, etc.

If you do not see the Toolbox window displayed click View on the menu bar, and then click Toolbox. This
should cause the Toolbox window to appear.

Common GUI controls found in Toolbox

Control Description
Label Displays images or uneditable text
TextBox Enables user to enter data via the keyboard. Also can be used to display editable or
uneditable text.
Button Triggers an event when clicked with the mouse.
CheckBox Specifies an option that can be selected (checked) or unselected (not checked)
ComboBox Provides a drop-down list of items from which the user can make a selection either
by clicking an item in the list or by typing in a box.
ListBox Provides a list of items from which the user can make a selection by clicking an item
in the list. Multiple elements can be selected.
Panel A container in which controls can be placed and organized
NumericUpDown Enables the user to select from a range of numeric input values

Event Handling
A user interacts with an application’s GUI to indicate the tasks that the application should perform. For
example, when you write an email in an email application, clicking the Send button tells the application to
send the email to the specified email address. GUIs are event driven. When the user interacts with a GUI
component, the interaction (known as an event) drives the program to perform a task. Common events (user
interactions) that might cause an application to perform a task include clicking a Button, typing in a Textbox,
selecting an item from a menu, closing a window and moving the mouse. A method that performs a task in
response to an event is called event hander. Event handling methods don’t return values, so they are
implemented as Sub procedures.

19
Example event handler to display a MessageBox when a Button is clicked is:

Public Class frmEvent

Private Sub btnClickMe_Click(sender As Object, e As EventArgs) Handles


[Link]
[Link]("Button was clicked.")
End Sub
End Class

Illustration on how to create the form and the event(s), First, create a new Windows application and add a
Button to the Form. In the Properties window for the Button, set the (Name) property to btnClickMe and the
Text property to Click Me. You’ll notice that each variable name we create for a control start with a three
letter code that abbreviates the type of the control (btn – Button, txt – TextBox, frm – Form, cmb –
ComboBox, lbl – Label, etc). this is a widely used naming convention in the Visual Basic community.

When the user clicks the Button in this example, we want the application to respond by displaying a
MessageBox. To do this, you must create an event handler for the Button’s Click event. You can create this
event handler by double clicking the Button on the Form, which declares the following empty event habdler
in the program code:

Private Sub btnClickMe_Click(sender As Object, e As EventArgs) Handles


[Link]

End Sub

By convention, Visual Basic names the event-handler method as controlName_eventName (e.g


btnClickMe_Click.

Each event handler receives two arguments. The first – an Object reference named sender – is a reference to
the object that generated the events. The second is a reference to an event arguments object (typically
named e) of type [Link] (or one of its derived classes). This object contains information about the
event that occurred. [Link] is the base class of all classes that represent event information.

To display a MessageBox in response to the event, insert the statement

[Link]("Button was clicked.")

20
In the event handler’s body.

When you execute the application and click the Button, a MessageBox appears displaying the text “Button
was clicked”

21

You might also like