Chapter Three
Chapter Three
3. Language Fundamentals
Data types determine the type of data that any variable can store. Data types are a broad
mechanism for declaring variables or functions of various types. A variable's type dictates how much
storage space it takes up and how the bit pattern recorded is interpreted. Variables belonging to
different data types are allocated different amounts of space in the memory. There are
various data types in VB.NET. They include:
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).
Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).
Date: allocated storage space of 8 bytes.
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.
A variable is simply the name provided to a storage location that the programs can access. Each
variable in VB.Net has a unique type, which governs the size and layout of the variable's memory,
the range of values that may be stored inside that memory, and the set of operations that can be
performed on the variable.
Data kinds have already been covered. The basic value types given by VB.Net are classified as follows:
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
Floating-point types Single and Double
Variable Declaration
Declaration of a variable involves giving the variable a name and defining the data type
to which it belongs.
We use the following syntax:
Dim Variable_Name as Data_Type
Here is an example of a valid variable declaration in VB.NET:
Dim x As Integer
In the above example, ‘x’ is the variable name while Integer is the data type to which
variable x belongs.
Use the following rules when you name procedures, constants, variables, and arguments
in a Visual Basic module:
You must use a letter as the first character.
You can't use a space, period (.), exclamation mark (!), or the characters @, &, $,
# in the name.
Name can't exceed 255 characters in length.
Generally, you shouldn't use any names that are the same as the
function,
statement,
method, and intrinsic constant names used in Visual Basic or by the host
application.
You can't repeat names within the same level of scope.
For example, you can't declare two variables named age within the same
procedure. However, you can declare a private variable named age and a
procedure-level variable named age within the same module.
Note
Visual Basic isn't case-sensitive, but it preserves the capitalization in the statement
where the name is declared.
Variable Initialization
Initializing a variable means assigning a value to the variable. Examples
1. Dim x As Integer
x = 10
‘or accepting from user
Console. WriteLine (“Please enter integer value”)
x= Console.ReadLine
2. Dim name As String
name = "Haftom"
or
Console. WriteLine (“Please enter your name”)
name = Console.ReadLine()
Constants can be of any basic data kinds, such as integers, characters, floating points, or string literals.
Enumeration constants are also available.
Constants are processed similarly to regular variables, except that their values cannot be changed after
they are defined.
Example
Const pi As Single = 3.14
OR
Const x = 10
Summary
Each variable must belong to a data type. The data type determines the amount of
memory space allocated to the variable.
We can convert a variable from one data type to another.
Initializing variables means assigning values to the variables.
We create a console application to help us get input from the users via the console
using the ReadLine function.
And use WriteLine () Function to display values and results.
Operating ON Strings
'write a program that accepts user name and password
'and check if the pass and username is correct "Login succeful" esle re-enter
Module Module1
Sub Main()s
Dim username, pass As String
Console.WriteLine("PLease enter your credentials")
l: username = Console.ReadLine
pass = Console.ReadLine
If username = "habtamu" And pass = 123 Then
MsgBox("LOGIN SUCCESSFULL", MsgBoxStyle.Critical)
Else
Console.WriteLine("WRONG USERNAME OR PASSWORD PLEASE ENTER AGAIN")
GoTo l
End If
End Sub
End Module
Module Module1
Sub Main()
Dim fname, lname, fullname, greetings As String
fname = "Chaltu"
lname = "Feyisa"
fullname = fname + " " + lname
Console.WriteLine("Full Name :" & fullname)
Console.ReadLine()
End Sub
End Module
a program proceeds through its statements from beginning to end. Some very simple programs
can be written with only this unidirectional flow. However, much of the power and utility of any
programming language comes from the ability to change execution order with control statements
and loops.
Control structures allow you to regulate the flow of your program's execution. Using control
structures, you can write Visual Basic code that makes decisions or that repeats actions.
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Statement Description
nested If You can use one If or Else if statement inside another If or Else
statements if statement(s).
nested Select You can use one select case statement inside another select
Case statements case statement(s).
3.3.1Control Statements
VB.Net provides the following types of decision-making statements. Click the following
links to check their details.
1. If Else Condition
Syntax
If condition Then
[Statement(s)]
End If
'Example Write a program that checks if the two values are the same,
' if they are the same it displays true else false
Module Module1
Sub Main()
Dim x, y As String
x = Console.ReadLine
y = Console.ReadLine
If x = y Then
Console.WriteLine("True")
Console.ReadLine()
Else
Console.WriteLine("False")
Console.ReadLine()
End If
End Sub
End Module
Example 2
2. Select Case
A Select Case statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each select case.
Syntax
Module Module1
Dim def As Char
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select def
Case "c"
Example 2:
Module Module1
End Module
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can
repeat the statements in a loop structure until a condition is True, until a condition is False, a
specified number of times, or once for each element in a collection.
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.
The following illustration shows a loop structure that runs a set of statements until a condition
becomes true:
While... End While It executes a series of statements as long as a given condition is True.
Exit statement Terminates the loop or select case statement and transfers execution to
the statement immediately following the loop or select case.
Continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
GoTo statement Transfers control to the labeled statement. Though it is not advised to
use GoTo statement in your program.
Examples :
1. Write a Vb.net Program that display 10-20 using for, while and do loops
2. Write a Vb.net Program that display 10-20 except 15 using for, while and do loops
Sub Main()
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
Example 2
'Define the While Loop Condition
While i < 20
If i = 15 Then
Console.WriteLine(" you Skipped {0}", i)
i += 1 ' skip the define iteration
Continue While
End If
Console.WriteLine(" Value of i is {0}", i)
i += 1 ' Update the variable i by 1
End While
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
Examples
1. Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
2. Dim a As Double
' for loop execution
For a = 10 To 20 Step 2.5
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer 'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop Until (a = 20)
Console.ReadLine()
End Sub
Continue Statement.
Example
Sub Main()
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
Example 2
'Define the While Loop Condition
While i < 20
If i = 15 Then
Console.WriteLine(" you Skipped {0}", i)
i += 1 ' skip the define iteration
Continue While
End If
Console.WriteLine(" Value of i is {0}", i)
Exit Statement
Sub Main()
'Declaration and initialization of variable i
Dim i As Integer = 10
If i = 15 Then
Console.WriteLine(" you Skipped {0}", i)
i += 1 ' skip the define iteration
Exit While
End If
Console.WriteLine(" Value of i is {0}", i)
We can create the Methods either by using Sub or Function keywords like as shown below. If we
create a method with Sub keyword that will not allow us to return any value. If you want to return any
value, you need to use Function keyword to create the method.
Syntax
<Access_Specifier> Sub Method_Name(<Parameters>)
// Statements to Execute
End Sub
Or
Module Module1
Sub Main()
Dim result As String = GetUserDetails("Haftom", 31)
Console.WriteLine(result)
GetDetails()
Console.ReadLine()
End Sub
Public Sub GetDetails()
Console.WriteLine("this is Using SUB Key word")
End Sub
Public Function GetUserDetails(ByVal name As String, ByVal age As
Integer) As String
Dim info As String = String.Format("Name: {0}, Age: {1}", name, age)
Return info
End Function
End Module
Example 2
Create two methods using function that accept values by values from main
function and display the sum and difference of two numbweers
Imports System
Module Find_Sum
' Create the SumOfTwo() Function and pass the parameters.
Function SumOfTwo(ByVal n1 As Integer, ByVal n2 As Integer) As
Integer
' Define the local variable.
Dim sum As Integer = 0
sum = n1 + n2
Return sum
End Function
Function SubtractionOfTwo(ByVal n1 As Integer, ByVal n2 As
Integer) As Integer
' Define the local variable.
Dim subtract As Integer
subtract = n1 - n2
Return subtract
End Function
Sub Main()
' Define the local variable a and b.
Dim a As Integer = 50
Dim b As Integer = 20
Dim total, total1 As Integer
Console.WriteLine(" First Number is : ", a)
Console.WriteLine(" Second Number is : ", b)
total = SumOfTwo(a, b) 'call SumOfTwo() Function
total1 = SubtractionOfTwo(a, b) 'call SubtractionOfTwo()
Function
Console.WriteLine(" Sum of two number is : ", total)
Console.WriteLine(" Subtraction of two number is :", total1)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Example Three
Q. Develop console simple calculator that performs
+,-,/,* and display an option to select the
operation. Make sure the values are from main method.
Imports System
Module Module1
Dim x As Double
Dim Y As Double
Dim ans As Double
Dim name As String
Sub Add()
Console.WriteLine(" please enter the first number ")
x = Console.ReadLine()
Console.WriteLine(" please enter the second number ")
Y = Console.ReadLine()
ans = x + Y
Console.WriteLine(" The submision is " & ans)
End Sub
Sub SUBS()
Console.WriteLine(" please enter the first number ")
x = Console.ReadLine()
Console.WriteLine(" please enter the second number ")
Y = Console.ReadLine()
ans = x - Y
Console.WriteLine(" The submision is " & ans)
End Sub
Sub MUL()
Console.WriteLine(" please enter the first number ")
x = Console.ReadLine()
Console.WriteLine(" please enter the second number ")
Y = Console.ReadLine()
ans = x * Y
Console.WriteLine(" The submision is " & ans)
End Sub
Sub DIV()
Console.WriteLine(" please enter the first number ")
x = Console.ReadLine()
Console.WriteLine(" please enter the second number ")
L: Y = Console.ReadLine()
If Y = 0 Then
Console.WriteLine("you can't devide By 0 Again!Enter 2nd
number")
GoTo L
End If
ans = x / Y
Console.WriteLine(" The submision is " & ans)
End Sub
Sub Main()
Console.WriteLine("================================")
l:
Console.WriteLine(" What Do you went to do?")
Console.WriteLine("________________________")
Console.WriteLine(" For Addtion enter + ")
Console.WriteLine(" For Substraction enter - ")
Console.WriteLine(" For Multiplication enter * ")
Console.WriteLine(" For Division enter / ")
Console.WriteLine(" to Exit enter Q / ")
Console.WriteLine("================================")
Dim choice As String = Console.ReadLine()
'Dim ch As String
If choice = "+" Then
Add()
GoTo l
'ch = Console.ReadLine()
ElseIf choice = "-" Then
SUBS()
GoTo l
Console.ReadLine()
ElseIf choice = "*" Then
MUL()
GoTo l
Console.ReadLine()
ElseIf choice = "/" Then
DIV()
GoTo l
Console.ReadLine()
Else
Console.ReadLine()
End If
End Sub
End Module
3.5 Events
Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are
examples of events. An event is an action that calls a function or may cause another event. Event
handlers are functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
Mouse events
This event gets triggered when the pointer of the mouse enters the
control.
Keyboard events
These are the events that are triggered when the events are fired upon
any action done on the keyboard. This includes actions such as
keypress, key down, enter, etc. Let us study some of the keyboard-
based events in detail.
A class is a group of different data members or objects with the same properties,
processes, events of an object, and general relationships to other member functions.
Furthermore, we can say that it is like a template or architect that tells what data and
function will appear when it is included in a class object. For example, it represents the
method and variable that will work on the object of the class.
Objects are the basic run-time units of a class. Once a class is defined, we can create any
number of objects related to the class to access the defined properties and methods.
For example, the Car is the Class name, and the speed, mileage, and wheels are
attributes of the Class that can be accessed by the Object.
We can create a class using the Class keyword, followed by the class name. And the
body of the class ended with the statement End Class.
Example
Q. create class Area_poly with at least two methods that calculate two area of different
polygons. Aone of them has to access the variables of the main class. As for the 2 nd method
pass the length and width by value.
Module Module1
Public Class Area_poly
Public length As Integer
Public width As Integer
Public Area As Double
Public Sub RECT(ByVal len, ByVal wid)
length = len
width = wid
Area = length * width
Console.WriteLine("area of the ectangle is " & Area)
Console.ReadKey()
End Sub
Public Sub TRIANGLE()
Area = (1 / 2) * length * width
Console.WriteLine("area of the ectangle is " & Area)
Console.ReadKey()
End Sub
End Class
Sub Main()
Dim l, w As Double
'Creating Object using c lass
Dim a As Area_poly = New Area_poly()
Console.WriteLine("please enter the length and width")
l = Console.ReadLine
w = Console.ReadLine
a.RECT(l, w)
' TRIANGLE ACCESSING CLASS VARIABLES DIRECTL USING
a.length = Console.ReadLine
a.width = Console.ReadLine
End Sub
End Module
Review Question