106LT Note2-1
106LT Note2-1
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:
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:
• 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.
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.
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.)
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.
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:
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()
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.
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.
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.
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.
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](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()
8
myPhone = New CellPhone
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.
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()
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
Derived 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"
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
Derived Class
Derived Class
12
End Sub
End Class
Test Module
Module Module1
Sub Main()
Dim myAnimal As Animal
Dim myDog As Dog
Dim myCat As Cat
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.
13
Module Module1
Sub Main()
ShowTax()
End Sub
Sub ShowTax()
Const TaxRate As Single = 0.08
[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:
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:
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")
[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:
ShowArray(numbers)
OOP example
16
Private name As String
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]()
greatestValue = [Link](arrayFixedValues)
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).
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.
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:
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:
End Sub
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.
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