Computer Programming 2
Computer Programming 2
Vision
Mission
ii
Table of Contents
Assessment Task 10
Summary 10
Assessment Task 19
Summary 20
Assessment Task 27
Summary 28
iii
Module 4: Visual Basic.Net Operators 29
Introduction 29
Learning Outcomes 29
Lesson 1. Arithmetic Operators 29
Lesson 2. Comparison Operators 31
Lesson 3. Logical Operators 33
Lesson 4. Assignment Operators 35
Assessment Task 37
Summary 38
iv
Course Code: CS2109
Course Requirements:
Assessment Tasks - 60%
Major Exams - 40%
_________
Periodic Grade 100%
v
MODULE 1
INTRODUCTION TO VISUAL BASIC.NET
PROGRAMMING
Introduction
Learning Outcomes
Like with all other NET languages, VB.NET supports object-oriented principles in full.
Everything in VB.NET is an object, with all the basic types (Short, Integer, Long, String,
Boolean, etc.) and the user-defined classes, events and even assemblies. The base Object
class inherits all properties. VB.NET is implemented through Microsoft's. NET Framework.
Therefore it has complete access to all libraries inside the Net Network. It is also possible to
1
run VB.NET programs on Mono, an open-source alternative to NET, not only under Windows
but also under Linux or Mac OSX (VB.Net, n.d.).
The following explanations make VB.Net a commonly used language of the profession
(VB.Net Environment Setup, n.d.) –
VB.Net has many strong programming features that make it endearing to many
programmers around the world (VB.Net Basic Syntax, n.d.).
Boolean Conditions
Automated Garbage Collection
Standard Library
Versioning Assembly
Properties and Events
Delegates and Events Management
Generics Facile to Use
Indexers
Conditional Compilation
Fast Multithreading
The Visual Basic language has undergone drastic changes, with its release for the NET
platform.
For example:
The language as such is now fully object-oriented
Visual Basic .Net programs and modules have full access to .Net
Framework, a robust level class library offering system and application services.
All applications built using Visual Basic .Net run the .Net common language
runtime within a controlled runtime environment.
2
Lesson 2. The .Net Framework
.Net framework is a pioneering platform that lets you write the following types of
applications (VB.Net Environment Setup, n.d.):
Windows applications
Web applications
Web services
Software are multi-platform software within the Net system. The program was
designed for use in any of the following languages: Visual Basic, C #, C++, Jscript, and
COBOL etc. All these languages can both access and communicate with the device. Net
database is an comprehensive collection of codes used by client languages like VB.Net. Such
languages use artefact-oriented processes (VB.Net Environment Setup, n.d.).
The last two are free. With these tools, all sorts of VB.Net programs can be written to
more complex applications, including simple command-line applications. Visual Basic Express
and Visual Web Developer Express edition have the same look and feel and Visual Studio
versions are stripped off (VB.Net Environment Setup, n.d.).
3
Although the NET Architecture runs on Windows OS, some alternative
implementations operate on other operating systems. Mono is a NET Platform open source
version that offers a Visual Basic compiler and runs on many operating systems including
various Linux and Mac OS flavors (VB.Net Environment Setup, n.d.).
The stated goal of Mono is not only to be able to run Microsoft NET cross-platform
applications but also to enhance development tools for Linux developers. Numerous operating
systems can run Mono, including Android, BSD, iOS, Linux , OS X, Windows, Solaris, and
UNIX (VB.Net Environment Setup, n.d.).
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Welcome to Laguna University!")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
The first line of the program Imports System is used to include the System namespace
in the program.
Totally object oriented, so every program needs to have a class module containing
the data and procedures the program uses.
4
Modules or classes will usually include more than one procedure. Procedures
include the executable code, or in other words, they describe the class behavior.
A procedure could be any of the following:
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent
The next line ('This program') is ignored by the compiler, and additional comments
have been added to the program.
The next line specifies the Main Procedure, the entry point for all VB.Net programs.
The Main procedure sets out what the module or class will do when it is run.
The Main procedure specifies its behavior with the statement Console.WriteLine
("Welcome to Laguna University!”) WriteLine is a method of the Console class defined
in the System namespace. This statement causes the message "Welcome to Laguna
University!" to be displayed on the screen.
The last line Console.ReadKey() is for the VS.NET Users. It would prevent the
computer from quickly running and closing when Visual Studio. NET begins the
program (VB.Net Basic Syntax, n.d.).
You can compile a VB.Net program by using the command line instead of the Visual Studio
IDE:
Open a text editor and add the above mentioned code.
Save the file as welcometoLU.vb
5
Open the command prompt tool and go to the directory where you saved the file.
Type vbc welcometoLU.vb and press enter to compile your code.
If there are no errors in your code the command prompt will take you to the next
line and would generate helloworld.exe executable file.
Next, type welcometoLU to execute your program.
You will be able to see "Welcome To Laguna Univesrsity" printed on the screen
(VB.Net Basic Syntax, n.d.)
Basic Syntax
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating, etc. An object is an
instance of a class.
Class - A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.
Instant Variables - Each object has its unique set of instant variables. An object's
state is created by the values assigned to these instant variables (VB.Net Basic
Syntax, n.d.).
For example, let us consider a Rectangle object. It does have characteristics such as
length and width. Depending on the architecture, it will need ways to recognize these attribute
values, measure area and display data (VB.Net Basic Syntax, n.d.).
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
6
'Public methods
Public Sub AcceptDetails
7
length = 4.5
width = 3.5
End Sub
End Sub
Let's look at the implementation of a rectangle class and discuss the basic syntax of VB.Net
on the basis of our observations: when the above code is compiled and executed, the
following results are produced:
The VB.Net system entry point is indicated by Sub Main. Here we use Class which includes
both code and data. Classes are used for object construction. For instance, r is a Rectangle
object in the code (VB.Net Basic Syntax, n.d.).
A class can have members, if defined, which can be accessed from outside class. Data
members are called fields and processes are called process members.
One can invoke shared methods or static methods without creating a class object. Methods
of instance are invoked via class object:
8
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
Identifiers
An identifier is a name used to identify a user-defined object, class, variable, function or any
other. The basic rules for naming classes in VB.Net are as follows:
A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ;
: " ' / and \. However, an underscore ( _ ) can be used.
It should not be a reserved keyword (VB.Net Basic Syntax, n.d.).
VB.Net Keywords
The following table lists the VB.Net reserved keywords:
9
Assessment Task
Summary
10
References
11
MODULE 2
VISUAL BASIC.NET FUNDAMENTALS (PART 1)
Introduction
Data types refer to a large system used to define variables or functions of different
types. A variable type defines how much storage space it occupies, and how it interprets the
stored bit pattern (VB.Net Operators, n.d.).
Learning Outcomes
Data types determine what type of data any individual can hold. Variables belonging to
various data types are given varying amount of space in the memory. VB.NET is composed
of various types of data. (VB.Net Operators, n.d.)
Including:
Boolean: the allocated storage depends on the platform of implementation. Its value
can be either True or False.
Byte: allocated storage space of 1 byte. Values range from 0 to 255 (unsigned).
12
Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).
Date: allocated storage space of 8 bytes. Values range from 0:00:00 (midnight)
January 1, 0001 to 11:59:59 PM of December 31, 9999.
Integer: has a storage space of 4 bytes. Values range between -2,147,483,648 to
2,147,483,647 (signed).
Long: has a storage space of 8 bytes. Numbers range from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807(signed).
String: The storage space allocated depends on the platform of implementation.
Values range from 0 to about 2 billion Unicode characters (VB.Net Operators, n.d.).
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean
b = 1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
Else
bl = False
End If
If bl Then
'the oath taking
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
13
Let us see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346
14
Converts the expression to UShort data type.
A variable is nothing other than a name given to a storage area which our programs
can control. Every variable in VB.Net has a different type, specifying the size and configuration
of the variable 's memory; the number of values that can be stored in that memory; and the
set of operations that can be applied to the variable (VB.Net Variables, n.d.).
Table 2.1 The basic value types provided in VB.Net can be categorized as (VB.Net Variables,
n.d.):
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long,
ULong and Char
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date
The statement Dim is used to declare variable and to assign storage for one or more
variables. The word Dim is used at the element, class, structure, method, or block stage.
Where,
Attributelist is a list of the attributes used by the variable. Optional.
accessmodifier defines the access levels of the variables, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
Shared declares a shared variable not associated with any particular instance of a
class or structure, but instead open to all class or structure instances.
Shadows mean that the variable re-declares and conceals an identically named
element or group of overloaded elements in a base class. Optional.
15
Static indicates that the variable will retain its value, even when the after termination
of the procedure in which it is declared. Optional.
ReadOnly means that the attribute is readable, but not writable. Optional.
WithEvents specifies that the variable is used by the instance assigned to the variable
to respond to the events posed. Optional.
Variablelist provides a list of the declared variables (VB.Net Variables, n.d.).
Each variable in the variable list has the following syntax and parts (VB.Net Variables,
n.d.):
variablename[([boundslist])][As [ New ] datatype ] [ = initializer ]
Where,
Some valid variable declarations along with their definition are shown here:
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression.
variable_name = value;
for example,
Dim pi As Double
16
pi = 3.14159
Try the following example which makes use of various types of variables:
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c = a + b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (assume
the user inputs Hello World):
17
Enter message: Hello World
Your Message: Hello World
lvalue : An expression which is a lvalue can appear as the left or right side of an
assignment.
rvalue : An expression that is a rvalue can appear on a given assignment's right but
not left side.
Variables are lvalues, and can thus appear on the left side of an assignment. Numeric
literals are rvalues and may therefore not be delegated and do not appear on the left side.
Following is a valid statement:
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error:
20 = g
Constants are described using Const statement in VB.Net. The Const statement is
used at entity, class, structure, process or block level for use instead of literal values (Vb.net
Constants, n.d.).
Where,
attributelist: specifies the list of attributes applied to the constants; you can provide
multiple attributes separated by commas. Optional.
Shadows: That makes the constant hide an identical name programming feature in a
base class.
Constantlist: Gives a list of names of the declared constants. Where, each constant
name has the syntax and sections below: constantname [ As datatype ] = initializer
constantname: specifies constant name
datatype: specifies constant data type
initializer: specifies the assigned value to the constant (Vb.net Constants, n.d.)
For example,
18
Private Const piValue As Double = 3.1415
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & Str(area))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Area = 153.933
Constant Description
vbCrLf Carriage return/linefeed character combination.
vbCr Carriage return character.
vbLf Linefeed character.
vbNewLine Newline character.
vbNullChar Null character.
vbNullString Not the same as a zero-length string (""); used for
calling external procedures.
vbObjectError Error number. User-defined error numbers should
be greater than this value. For example:
Err.Raise(Number) = vbObjectError + 1000
vbTab Tab character.
vbBack Backspace character.
Assessment Task
I. Write VB.NET code to declare two integer variables, one float variable, and one
string variable and assign 10, 15, 12.5, and "VB.NET programming" to them
respectively.
II. Write a program that declare the following constants:
19
a. Declare a constant named “Pi” and place a floating point value
3.141592653589.
b. Declare a constant named “Square root of 2” and place a value of
1.41421356237
c. Declare a public constant named “message” and place a string value of
“WELCOME TO LAGUNA UNIVERSITY!”
Summary
References
20
MODULE 3
VISUAL BASIC.NET FUNDAMENTALS (PART 2)
Introduction
The constants apply to fixed values which cannot be changed by the program during
its execution. Even certain set values are called literals. Constants may be an integral
constant, a floating constant, a character constant or a string literal in all of the basic data
types. Also there are constants in enumeration. The constants are treated much like normal
variables, except that after their creation, their values cannot be changed. An enumeration is
a set of constants called by integer (Vb.net Constants, n.d.).
Learning Outcomes
An enumerated type is specified through the declaration Enum. Enum 's declaration sets an
enumeration, which defines the principles of its leaders. The Enum statement may be used
on node, class, structure, process or block point (Vb.net Constants, n.d.).
The syntax for the Enum statement is as follows (Vb.net Constants, n.d.):
Where,
enumerationname: name of the enumeration. Required
datatype: specifies the data type of the enumeration and all its members.
21
memberlist: specifies the list of member constants being declared in this statement
required.
Each member in the memberlist has the following syntax and parts (Vb.net Constants, n.d.):
[< attribute list>] member name [ = initializer ]
Where,
name: specifies the name of the member. Required.
initializer: value assigned to the enumeration member. Optional.
For example,
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
The following example demonstrates declaration and use of the Enum variable Colors:
Module constantsNenum
Enum Colors
red = 5
orange = 4
yellow = 3
green = 2
azure = 1
blue = 0
violet = 10
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Azure is : " & Colors.azure)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
22
Lesson 2. Modifiers
The modifiers are keywords associated with each programming element to illustrate
how to act or access the programming element in the program. The access modifiers, for
example: Public, Private, Protected, Friend, Protected Friend, etc., signify the level of access
of a programming feature like a variable, constant, enumeration, or class (VB.Net Modifiers,
n.d.).
Modifier Description
Ansi Specifies that Visual Basic should marshal all strings to American National Standards Institute
(ANSI) values regardless of the name of the external procedure being declared.
Assembly Specifies that an attribute at the beginning of a source file applies to the entire assembly.
Async Indicates that the method or lambda expression that it modifies is asynchronous. Such methods
are referred to as async methods. The caller of an async method can resume its work without
waiting for the async method to finish.
Auto The charsetmodifier part in the Declare statement supplies the character set information for
marshaling strings during a call to the external procedure. It also affects how Visual Basic searches
the external file for the external procedure name. The Auto modifier specifies that Visual Basic
should marshal strings according to .NET Framework rules.
ByRef Specifies that an argument is passed by reference, i.e., the called procedure can change the value
of a variable underlying the argument in the calling code. It is used under the contexts of:
Declare Statement
Function Statement
Sub Statement
ByVal Specifies that an argument is passed in such a way that the called procedure or property cannot
change the value of a variable underlying the argument in the calling code. It is used under the
contexts of:
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
Default Identifies a property as the default property of its class, structure, or interface.
Friend Specifies that one or more declared programming elements are accessible from within the
assembly that contains their declaration, not only by the component that declares them.
Friend access is often the preferred level for an application's programming elements, and Friend is
the default access level of an interface, a module, a class, or a structure.
In It is used in generic interfaces and delegates.
Iterator Specifies that a function or Get accessor is an iterator. Aniterator performs a custom iteration over
a collection.
Key The Key keyword enables you to specify behavior for properties of anonymous types.
Module Specifies that an attribute at the beginning of a source file applies to the current assembly module.
It is not same as the Module statement.
MustInherit Specifies that a class can be used only as a base class and that you cannot create an object
directly from it.
23
MustOverride Specifies that a property or procedure is not implemented in this class and must be overridden in a
derived class before it can be used.
Narrowing Indicates that a conversion operator (CType) converts a class or structure to a type that might not
be able to hold some of the possible values of the original class or structure.
NotInheritable Specifies that a class cannot be used as a base class.
NotOverridable Specifies that a property or procedure cannot be overridden in a derived class.
Optional Specifies that a procedure argument can be omitted when the procedure is called.
Out For generic type parameters, the Out keyword specifies that the type is covariant.
Overloads Specifies that a property or procedure redeclares one or more existing properties or procedures
with the same name.
Overridable Specifies that a property or procedure can be overridden by an identically named property or
procedure in a derived class.
Overrides Specifies that a property or procedure overrides an identically named property or procedure
inherited from a base class.
ParamArray ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray
parameter is always declared using ByVal.
Partial Indicates that a class or structure declaration is a partial definition of the class or structure.
Private Specifies that one or more declared programming elements are accessible only from within their
declaration context, including from within any contained types.
Protected Specifies that one or more declared programming elements are accessible only from within their
own class or from a derived class.
Public Specifies that one or more declared programming elements have no access restrictions.
ReadOnly Specifies that a variable or property can be read but not written.
Shadows Specifies that a declared programming element redeclares and hides an identically named
element, or set of overloaded elements, in a base class.
Shared Specifies that one or more declared programming elements are associated with a class or
structure at large, and not with a specific instance of the class or structure.
Static Specifies that one or more declared local variables are to continue to exist and retain their latest
values after termination of the procedure in which they are declared.
Unicode Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of
the external procedure being declared.
Widening Indicates that a conversion operator (CType) converts a class or structure to a type that can hold
all possible values of the original class or structure.
WithEvents Specifies that one or more declared member variables refer to an instance of a class that can raise
events.
WriteOnly Specifies that a property can be written but not read.
Lesson 3. Statements
24
Executable statements - These are the declarations that trigger actions. Those
statements may call a method or function, loop or branch to a variable or constant
through blocks of code or assign values or expression. For the last case it is called a
Declaration of Assignment (VB.NET Statements, n.d.).
Declaration Statements
The declaration statements are used for naming and defining processes, variables,
resources, arrays, and constants. Also, when you declare a programming element you can
specify their data type, access level and scope (VB.NET Statements, n.d.).
The programming elements that you may declare include variables, constants,
enumerations, classes, structures, modules, interfaces, method parameters, function returns,
references to external procedures, operators, properties, events, and delegates (VB.NET
Statements, n.d.).
Table 3.2 Following are the declaration statements in VB.Net (VB.NET Statements, n.d.):
Const Statement Declares and defines one or more constants. Const high As Long = 1000
Const naturalLogBase As Object
= CDec(2.7182818284)
Enum Statement Declares an enumeration and defines the values of its Enum ShirtSize
members. ExtraLarge
Large
Medium
Small
End Enum
Class Statement Class Box
Declares the name of a class and introduces the definition of the variables, Public length As Double
properties, events, and procedures that the class comprises. Public breadth As Double
Public height As Double
End Class
Structure Statement Structure Box
Declares the name of a structure and introduces the definition of the Public length As Double
variables, properties, events, and procedures that the structure comprises. Public breadth As Double
Public height As Double
End Structure
Module Statement Public Module myModule
Declares the name of a module and introduces the definition of the variables, Sub Main()
properties, events, and procedures that the module comprises. Dim user As String =
InputBox("What is your real name?")
MsgBox("Real name is" & user)
End Sub
End Module
25
Interface Statement Public Interface MyInterface
Declares the name of an interface and introduces the definitions of the Sub doSomething()
members that the interface comprises. End Interface
Function Statement Function myFunction
Declares the name, parameters, and code that define a Function procedure. (ByVal n As Integer) As Double
Return 5.87 * n
End Function
Sub Statement Sub mySub(ByVal s As String)
Declares the name, parameters, and code that define a Sub procedure. Return
End Sub
Declare Statement Declare Function getUserName
Declares a reference to a procedure implemented in an external file. Lib "advapi32.dll"
Alias "GetUserNameA"
(ByVal lpBuffer As String,
ByRef nSize As Integer) As Integer
Operator Statement Public Shared Operator +
Declares the operator symbol, operands, and code that define an operator (ByVal x As obj, ByVal y As obj) As obj
procedure on a class or structure. Dim r As New obj
' implemention code for r = x + y
Return r
End Operator
Executable Statements
An action is executed by an executable sentence. Executable statements are
statements that call a process, branch to a specific location in the code, loop through several
statements or evaluate an expression. An assignment statement is a particular case of an
executable declaration (VB.NET Statements, n.d.).
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10
' check the boolean condition using if statement '
If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")
26
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Assessment Task
I. Identification
a. It specifies the data type of the enumeration and all its members.
b. It specifies that one or more declared member variables refer to an instance
of a class that can raise events.
c. It specifies that a property or procedure redeclares one or more existing
properties or procedures with the same name.
d. It declares a reference to a procedure implemented in an external file.
e. It associated on each programming element to illustrate how to act or access
the programming element in the program.
f. It specifies that one or more declared programming elements are associated
with a class or structure at large, and not with a specific instance of the class
or structure.
g. What is the meaning of the abbreviation ANSI?
h. Those statements may call a method or function, loop or branch to a variable
or constant through blocks of code or assign values or expression.
i. It is optional and the value assigned to the enumeration member.
j. It declares and defines one or more constants.
k. It specifies that one or more declared programming elements are accessible
only from within their declaration context, including from within any contained
types.
l. These are statements in which you name a variable, constant or procedure
and you can also specify the type of data.
m. It specifies the list of member constants being declared in this statement
required.
n. It indicates that a conversion operator (CType) converts a class or structure
to a type that can hold all possible values of the original class or structure.
o. Declares the name of a module and introduces the definition of the variables,
properties, events, and procedures.
27
II. Create a program that will declare and allocate storage space. Use the following
variables and data types.
a. Employee Name – String
b. Employee Salary – Integer
c. Sex – String
d. Employment Status -String
Summary
References
28
MODULE 4
VISUAL BASIC.NET OPERATORS
Introduction
Learning Outcomes
Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then (VB.Net Operators, n.d.) –
29
MOD Modulus Operator and B MOD A will give 1
remainder of after an integer
division
Try the following example to understand all the arithmetic operators available in
VB.Net (VB.Net Operators, n.d.):
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
Dim p As Integer = 2
Dim c As Integer
Dim d As Single
c=a+b
Console.WriteLine("Line 1 - Value of c is {0}", c)
c=a-b
Console.WriteLine("Line 2 - Value of c is {0}", c)
c=a*b
Console.WriteLine("Line 3 - Value of c is {0}", c)
d=a/b
Console.WriteLine("Line 4 - Value of d is {0}", d)
c=a \b
Console.WriteLine("Line 5 - Value of c is {0}", c)
c = a Mod b
Console.WriteLine("Line 6 - Value of c is {0}", c)
c=b^p
Console.WriteLine("Line 7 - Value of c is {0}", c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.1
Line 5 - Value of c is 2
Line 6 - Value of c is 1
Line 7 - Value of c is 100
30
Lesson 2. Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then (VB.Net Operators, n.d.):
Try the following example to understand all the relational operators available in
VB.Net (VB.Net Operators, n.d.)
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
If (a = b) Then
31
Console.WriteLine("Line 1 - a is equal to b")
Else
Console.WriteLine("Line 1 - a is not equal to b")
End If
If (a < b) Then
Console.WriteLine("Line 2 - a is less than b")
Else
Console.WriteLine("Line 2 - a is not less than b")
End If
If (a > b) Then
Console.WriteLine("Line 3 - a is greater than b")
Else
Console.WriteLine("Line 3 - a is not greater than b")
End If
' Lets change value of a and b
a=5
b = 20
If (a <= b) Then
Console.WriteLine("Line 4 - a is either less than or equal to b")
End If
If (b >= a) Then
Console.WriteLine("Line 5 - b is either greater than or equal to b")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)–
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Apart from the above, VB.Net provides three more comparison operators, which we
will be using in forthcoming chapters; however, we give a brief description here (VB.Net
Operators, n.d.).
Is Operator − It compares two object reference variables and determines if two
object references refer to the same object without performing value comparisons. If
32
object1 and object2 both refer to the exact same object instance, result is True;
otherwise, result is False.
IsNot Operator − It also compares two object reference variables and determines if
two object references refer to different objects. If object1 and object2 both refer to
the exact same object instance, result is False; otherwise, result is True.
Like Operator − It compares a string against a pattern.
Following table shows all the logical operators supported by VB.Net. Assume
variable A holds Boolean value True and variable B holds Boolean value False, then
(VB.Net Operators, n.d.)−
33
Try the following example on next page to understand all the logical/bitwise
operators available in VB.Net (VB.Net Operators, n.d.)−
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'bitwise And, Or and Xor Checking
If (c And d) Then
Console.WriteLine("Line 4 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 5 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 6 - Condition is true")
End If
'Only logical operators
If (a AndAlso b) Then
Console.WriteLine("Line 7 - Condition is true")
End If
If (a OrElse b) Then
Console.WriteLine("Line 8 - Condition is true")
End If
' lets change the value of a and b
a = False
b = True
If (a And b) Then
Console.WriteLine("Line 9 - Condition is true")
Else
Console.WriteLine("Line 9 - Condition is not true")
End If
If (Not (a And b)) Then
34
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)−
35
^= Exponentiation and assignment operator. It raises the left C^=A is equivalent to C =
operand to the power of the right operand and assigns C^A
the result to left operand.
<<= Left shift AND assignment operator C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C =
C >> 2
&= Concatenates a String expression to a String variable or Str1 &= Str2 is same as
property and assigns the result to the variable or property. Str1 = Str1 & Str2
Try the following example to understand all the assignment operators available in VB.Net
(VB.Net Operators, n.d.)−
Module assignment
Sub Main()
Dim a As Integer = 21
Dim pow As Integer = 2
Dim str1 As String = "Hello! "
Dim str2 As String = "VB Programmers"
Dim c As Integer
c=a
Console.WriteLine("Line 1 - = Operator Example, _
Value of c = {0}", c)
c += a
Console.WriteLine("Line 2 - += Operator Example, _
Value of c = {0}", c)
c -= a
Console.WriteLine("Line 3 - -= Operator Example, _
Value of c = {0}", c)
c *= a
Console.WriteLine("Line 4 - *= Operator Example, _
Value of c = {0}", c)
c /= a
Console.WriteLine("Line 5 - /= Operator Example, _
Value of c = {0}", c)
c = 20
c ^= pow
Console.WriteLine("Line 6 - ^= Operator Example, _
Value of c = {0}", c)
c <<= 2
Console.WriteLine("Line 7 - <<= Operator Example,_
Value of c = {0}", c)
c >>= 2
36
Console.WriteLine("Line 8 - >>= Operator Example,_
Value of c = {0}", c)
str1 &= str2
Console.WriteLine("Line 9 - &= Operator Example,_
Value of str1 = {0}", str1)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (VB.Net
Operators, n.d.)−
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
xLine 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - ^= Operator Example, Value of c = 400
Line 7 - <<= Operator Example, Value of c = 1600
Line 8 - >>= Operator Example, Value of c = 400
Line 9 - &= Operator Example, Value of str1 = Hello! VB Programmers
Assessment Task
I. Code in VB.NET program to allow the user to input two integer values and then the
program print the results of adding, subtracting, multiplying, and dividing among
the two values. See the output below:
a. Enter value a:30
b. Enter value b:10
c. The result of adding is 40.
d. The result of subtracting is 20;
e. The result of multiplying is 300.
f. The result of dividing is 3.
II. Code in VB.NET program to allow the user to input the amount of deposit, yearly
interest rate (percentage), and income tax(percentage). Then the program will
calculate the amount of interest that the person earns in the year. See the output
below:
a. The amount of deposit: 1000
b. Yearly interest rate: 7.5%
c. Income tax rate: 4%
d. The amount of interest earned in the year:71.0
37
III. Code in VB.NET program to allow the user to input two float values and then the
program adds the two values together.
The result will be assigned to the first variable.
a. Enter value a:12.5
b. The value of a before adding is 12.5.
c. Enter value b:34.9
d. The value of a after adding is 47.4
Summary
References
38