Visual Basic Complete Notes
Visual Basic Complete Notes
Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for negative
values;
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"
bl = True
Else
bl = False
End If
If bl Then
End If
Console.ReadKey()
End Sub
End Module
Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in VB.Net has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong
and Char
Some valid variable declarations along with their definition are shown here:
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
Example
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.ReadLine()
End Sub
End Module
message = Console.ReadLine
Module variablesNdataypes
Sub Main()
message = Console.ReadLine
Console.WriteLine()
Console.ReadLine()
End Sub
End Module
Constants
Declaring Constants
In VB.Net, constants are declared using the Const statement.
For example,
'The following statements declare constants.'
Example
The following example demonstrates declaration and use of a constant
value:
Module constantsNenum
Sub Main()
Const PI = 3.14149
radius = 7
Console.ReadKey()
End Sub
End Module
Statements
A statement is a complete instruction in Visual Basic programs. It may
contain keywords, operators, variables, literal values, constants and
expressions.
Declaration statements - these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.
Executable statements - these are the statements, which initiate actions. These statements
can call a method or function, loop or branch through blocks of code or assign values or
expression to a variable or constant. In the last case, it is called an Assignment statement.
Declaration Statements
The declaration statements are used to name and define procedures,
variables, properties, arrays, and constants. When you declare a
programming element, you can also define its data type, access level,
and scope.
The programming elements you may declare include variables,
constants, enumerations, classes, structures, modules, interfaces,
procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
Following are the declaration statements in VB.Net:
4 Class Box
Class Statement
Public length As Double
Declares the name of a class and introduces the definition of
Public breadth As Double
the variables, properties, events, and procedures that the
Public height As Double
class comprises.
End Class
5 Structure Box
Structure Statement
Public length As Double
Declares the name of a structure and introduces the
Public breadth As Double
definition of the variables, properties, events, and
Public height As Double
procedures that the structure comprises.
End Structure
End Sub
End Module
8 Function myFunction
Function Statement
(ByVal n As Integer) As Double
Declares the name, parameters, and code that define a
Return 5.87 * n
Function procedure.
End Function
Return r
End Operator
) As Double
Executable Statements
An executable statement performs an action. Statements calling a
procedure, branching to another place in the code, looping through
several statements, or evaluating an expression are executable
statements. An assignment statement is a special case of an
executable statement.
Example
The following example demonstrates a decision making statement:
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")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then:
Show Examples
Comparison Operators
Following table shows all the comparison operators supported by VB.Net.
Assume variable A holds 10 and variable B holds 20, then:
Show Examples
<> Checks if the values of two operands are equal or not; if (A <> B)
values are not equal, then condition becomes true. is true.
> Checks if the value of left operand is greater than the value (A > B) is
of right operand; if yes, then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand; if yes, then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal (A >= B)
to the value of right operand; if yes, then condition is not
becomes true. true.
<= Checks if the value of left operand is less than or equal to (A <= B)
the value of right operand; if yes, then condition becomes is true.
true.
Assignment Operators
There are following assignment operators supported by VB.Net:
Show Examples
Str1 =
Str1 &
Str2
Decision Making
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
If Then Else
Info:We see if the user typed "1" or
"2" and pressed return. We also
display the output.
VB.NET program that uses ReadLine
Module Module1
Sub Main()
While True
End While
End Sub
End Module
Output
1
One
You typed 1
2
Two
You typed 2
3
You typed 3
Example:
Module decisions
Sub Main()
Dim a As Integer = 100
If (a = 10) Then
Console.WriteLine("Value of a is 10")
ElseIf (a = 20) Then
Console.WriteLine("Value of a is 20")
ElseIf (a = 30) Then
Console.WriteLine("Value of a is 30")
Else
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact 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:
Syntax:
The syntax for a Select Case statement in VB.Net is as follows:
Where,
expression: is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short,
Single, String, UInteger, ULong, and UShort.
expressionlist: List of expression clauses representing match values for expression. Multiple
expression clauses are separated by commas.
statements: statements following Case that run if the select expression matches any clause
in expressionlist.
elsestatements: statements following Case Else that run if the select expression does not
match any clause in the expressionlist of any of the Case statements.
Flow Diagram:
Example:
Module Module1
Sub Main()
When the above code is compiled and executed, it produces the following
result:
Well done
Your grade is B
Loops
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.
VB.Net provides the following control statements. Click the following links to
check their details.
Module loops
Sub Main()
Dim a As Integer = 10
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Console.ReadLine()
End Sub
End Module
Module loops
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
End Module
Module loops
Sub Main()
Dim a As Integer = 10
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module
Nested Loops
Example:
The following program uses a nested for loop to find the prime numbers
from 2 to 100:
Module loops
Sub Main()
Dim i, j As Integer
For i = 2 To 100
For j = 2 To i
Exit For
End If
Next j
End If
Next i
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Arrays
An array stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
You can also initialize the array elements while declaring the array. For
example,
The elements in an array can be stored and accessed by using the index of
the array. The following program demonstrates this:
Module arrayApl
Sub Main()
Dim i, j As Integer
For i = 0 To 10
For j = 0 To 10
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as
par the need of the program. You can declare a dynamic array using
the ReDimstatement.
Where,
The Preserve keyword helps to preserve the data in an existing array, when you resize it.
arrayname is the name of the array to re-dimension.
subscripts specifies the new dimension.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
re-release material May/June 2015
Here is a copy of the pre-release material
Task1
A school keep records of the weights of each pupil. The weight in kilograms of each
pupil is recorded on the first day of term. Input and store the weights and names
recorded for a class of 30 pupils. You must store the weights in a one-dimensional array
and the names in another one-dimensional array. All the weights must be validated on
entry and any invalid weights rejected. You must decide your own validation rules. You
must assumethatthepupilsnamesareunique.Outputthenamesandweightsofthepupilsin the
class.
Task2
The weight in kilograms of each pupil is recorded again
onthelastdayofterm.Calculateandstorethedifferenceinweightforeachpupil.
Task3
Forthosepupilswhohaveadifferenceinweightofmorethan2.5kilograms,output,
withasuitablemessage,thepupil’sname,thedifferenceinweightandwhetherthisis rise or a
fall. Your program must include appropriate prompts for the entry of data.
Errormessagesandotheroutputsneedtobesetoutclearlyandunderstandably.All variables,
constants and other identifiers must have meaningful names. Each task must be fully
tested.
‘Task 2
Dim weight2(30), Weight_Difference(30) AsSingle
For Count = 1 To 30
Console.WriteLine(Count & " " & Name(Count) & " " & Weight1(Count))
Console.Write("Enter weight on last day ")
weight2(Count) = Console.ReadLine()
'Validation Check for Weight
While weight2(Count) < Lower_Limit Or weight2(Count) > Upper_Limit
Console.WriteLine("Error: Invalid weight. It must be between 5 and 500")
Console.Write("Re-enter weight on lastt day ")
weight2(Count) = Console.ReadLine()
EndWhile
Weight_Difference(Count) = weight2(Count) - Weight1(Count)
Next
'Task 3
For Count = 1 To 30
If Weight_Difference(Count) > 2.5 Then
Console.WriteLine(Name(Count) & " has a rise in weight of " & Weight_Difference(Count) & " kg")
ElseIf Weight_Difference(Count) < -2.5 Then
Console.WriteLine(Name(Count) &" has a fall in weight of "& Weight_Difference(Count) &" kg")
EndIf
Next
Console.ReadKey()
EndSub
EndModule
Pre-release material
A teacher needs a program to record marks for a class of 30 students who have sat three
computer
science tests.
Write and test a program for the teacher.
• Your program must include appropriate prompts for the entry of data.
• Error messages and other output need to be set out clearly and understandably.
• All variables, constants and other identifiers must have meaningful names.
You will need to complete these three tasks. Each task must be fully tested.
TASK 1 – Set up arrays
Set-up one dimensional arrays to store:
• Student names
• Student marks for Test 1, Test 2 and Test 3
o Test 1 is out of 20 marks
o Test 2 is out of 25 marks
o Test 3 is out of 35 marks
• Total score for each student
Input and store the names for 30 students. You may assume that the students’ names are unique.
Input and store the students’ marks for Test 1, Test 2 and Test 3. All the marks must be validated
on
entry and any invalid marks rejected.
TASK 2 – Calculate
Calculate the total score for each student and store in the array.
Calculate the average total score for the whole class.
Output each student’s name followed by their total score.
Output the average total score for the class.
TASK 3 – Select
Select the student with the highest total score and output their name and total score.
Ans:
Pseudocode
If Condition
Begin
Input marks
If marks >= 60
End
Case Statement
Begin
Input Marks
Case Marks of
Case =100
Print “Perfect Score”
Case > 89
Print “Grade = A”
Case > 79
Print “Grade = B”
Case > 69
Print “Grade = C”
Case > 59
Print “Grade = D”
Otherwise
Print “Grade = F”
End Case
End
Or
Begin
Input grade
CASE grade OF
“A” : points = 4
“B” : points = 3
“C” : points = 2
“D” : points = 1
“F” : points = 0
Otherwise : print “ invalid grade”
ENDCASE
Output points
End
Q: Input two numbers and a mathematical symbol from user and output total.
Total should be the sum of two numbers if the mathematical symbol is “+”
Total should be the difference of two numbers if the mathematical symbol is “-”
Total should be the product of two numbers if the mathematical symbol is “*”
Total should be the coefficient of two numbers if the mathematical symbol is “/”
Else display “invalid operator”
Pseudocode
Begin
Input num1, num2, symbol
CASE symbol OF
“+” : total = num1 + num2
“-” : total = num1 - num2
“*” : total = num1 * num2
“/” : total = num1 / num2
otherwise : print “Invalid symbol”
ENDCASE
Output total
End
Q2: You have been asked to choose the correct routine from the menu shown below.
a) Decide which type of conditional statement are you going to you use.
b) Explain your choice.
c) Write the Pseudocode
d) Select your test data and explain why you choose each value.
Answer:
Input Choice
Case Choice of
1 : SetUpNewAccount;
2 : MakeChangesToAnExistingAccount;
3: CloseAnAccount;
4 : ViewMyOrders;
5 : PlaceANewOrder;
6 : AlterAnExistingOrder;
0 : Exit;
H : Help;
End Case
End
Q3: Show three ways to use a loop to add up five numbers and print out the total can be set up using
Pseudocode. Explain which loop is the most efficient to use.
Pseudocode
Answer:
There are three different loop structures that we can use to add five numbers.
Begin
Sum=0
For Count = 1 to 5
Input Num
Next Count
End
Begin
Sum=0
Count = 0
Repeat
Input Num
Until Count = 5
End
Begin
Sum=0
Count = 0
Input Num
Count = Count + 1
EndWhile
End
Q4: A sweets shop sells five hundred different types of sweets. Each sort of sweet is identified by a
different four digit code. All sweets that start with 1 are Chocolates, All sweets that start with 2 are
toffees, All sweets that start with 3 are jellies and all other sweets are miscellaneous and can start with
any other digit except zero.
a) Write an algorithm, using a flowchart or Pseudocode which input the four digit code for all 500
items and output the number of chocolates, toffees and jellies.
b) Explain how you would test your flow chart.
c) Decide the test data to use and complete a trace table showing a dry run of your flow chart.
Answer:
Pseudocode
Begin
TotalChocolate = 0
TotalToffees = 0
TotalJellies = 0
For Count = 1 to 500
Input Code
If Code >= 1000 And Code <=1999
Then TotalChocolate = TotalChocolate + 1
Else
If Code >= 2000 And Code <=2999
Then TotalToffees = TotalToffees + 1
Else
If Code >= 3000 And Code <=3999
Then TotalJellies = TotalJellies + 1
End If
End If
End If
Next Count
Output “Total Number Of Chocolates :” , TotalChocolate
Output “Total Number Of Toffees :” , TotalToffees
Output “Total Number Of Jellies :” , TotalJellies
End
Q5: The temperature in an apartment must be kept between 18⁰C and 20⁰C. If the temperature
reaches 22⁰C then the fan is switched On; If the temperature reaches 16⁰C then the heater is
switched On; otherwise the fan and the heater are switched Off. The following library routines
are available:
GetTemperature
FanOn
FanOff
HeaterOn
HeaterOff
Write an algorithm using Pseudocode or flow chart, to keep the temperature at the right level.
Pseudocode
Begin
Temperature = GetTemperature;
If Temperature >= 22
Then FanOn;
Else
If Temperature <= 16
Then HeaterOn;
Else
FanOff;
HeaterOff;
End If
End If
End
Q6: Daniel lives in Italy and travels to Mexico, India and New Zealand. The time difference are:
VB program
Module Module1
Sub Main( )
Dim Tbun, Tcoffee, Tcake, Tsandwich, Tdessert, quantity, TotalTakings, HighestTaking As Integer
Tbun =0
Tcoffee =0
Tcake =0
Tsandwich = 0
Tdessert =0
Dim Item As String
Do
Console.writeline ( “Enter the item in lower case only”)
Item = console.readline( )
Console.writeline ( “Enter its quantity”)
quantity = Int(console.readline( ))
Select Item
Case “bun”
Tbun = Tbun + quantity
Case “coffee”
Tcoffee = Tcoffee + quantity
Case “cake”
Tcake = Tcake + quantity
Case “sandwich”
Tsandwich = Tsandwich + quantity
Case “dessert”
Tdessert = Tdessert + quantity
Case Else
Console.writeline(“ Enter relevant product ”)
End Select
Loop Until ( Item = “End” )
TotalTakings = Tbun + Tcoffee + Tcake + Tsandwich + Tdessert
Console.writeline(“The total takings of the whole day” & TotalTakings)
If (Tbun > HighestTaking) Then
HighestTaking = Tbun
Item = “Bun”
End If
If (Tcoffee > HighestTaking) Then
HighestTaking = Tcoffee
Item = “Coffee”
End If
If ( Tcake > HighestTaking) Then
HighestTaking = Tcake
Item = “Cake”
End If
If ( Tsandwich > HighestTaking) Then
HighestTaking = Tsandwich
Item = “Sandwich”
End If
If (Tdessert > HighestTaking) Then
HighestTaking = Tdessert
Item = “Dessert”
End If
Console.writeline(“The item which has the highest sales today is : ” & Item)
Console.readkey( )
End Sub
End Module
Q9: 5000 numbers are being input which should have either one digit, two digits, three digits or four digits. Write an
algorithm which:
Input 5000 numbers
Output how many numbers have one digit, two digits, three digits and four digits.
Output the percentage of numbers which were outside the range.
Pseudocode
Begin
OneDigit = 0
TwoDigit = 0
ThreeDigit = 0
FourDigit = 0
OutSide = 0
For Count = 1 to 500
Input Number
If Number >= 0 And Number <=9
Then OneDigit = OneDigit + 1
Else
If Number >= 10 And Number <=99
Then TwoDigit = TwoDigit + 1
Else
If Number >= 100 And Number <=999
Then ThreeDigit = ThreeDigit + 1
Else
If Number >= 1000 And Number <=9999
Then FourDigit = FourDigit + 1
Else
OutSide = OutSide + 1
End If
End If
End If
End If
Next Count
Percentage = OutSide / 5000 * 100
Output “Total Number Of One Digit Numbers :” , OneDigit
Output “Total Number Of Two Digit Numbers :” , TwoDigit
Output “Total Number Of Three Digit Numbers :” , ThreeDigit
Output “Total Number Of Four Digit Numbers :” , FourDigit
Output “Percentage of numbers outside the range” , Percentage
End