M.Mushtaq: Download and Setup
M.Mushtaq: Download and Setup
http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express
If you don’t run Windows as your operating system you can try using Mono
http://www.go-mono.com/mono-downloads/download.html
aq
Start a new Project and select Console Application. Type the following code:
module module1
sub main()
end sub
end module
console.readKey()
ht
console.writeline("Hello World!")
us
(Press F5 to run the code)
.M
Tasks
0.2 – Write a program that displays the message “My name is Dave and I live in Brussels” (replace
Dave and Brussels with your own information)
0.3 – Write a program that displays the lyrics to your national anthem. Each line of the song should
be on a fresh line.
Module Module1
Sub Main()
Console.WriteLine("This is the first line of the program. It will be executed
first.")
Console.ReadKey()
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("But then the colour changes to Red.")
Console.ReadKey()
Console.BackgroundColor = ConsoleColor.White
Console.WriteLine("And the background goes white")
Console.ReadKey()
aq
Console.ResetColor()
Console.WriteLine("But it's okay. We can reset it")
Console.ReadKey()
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine("The order of lines of code is important")
Console.ReadKey()
End Sub ht
Console.WriteLine("We start at the top and work down")
us
End Module
.M
Tasks
1.1) Display the words red, amber, green on a fresh line each in order on the screen. Colour the
words appropriately.
M
1.2) Displaythe names of the colours of the rainbow. Each on a separate line, coloured and in order.
Example Program 2 - Assignment - Integer, byte, real, boolean, character, string, date/time.
Module Module1
Sub Main()
theWord = "Bird"
theNumber = 9
aq
Console.ReadKey()
theWord = "Cat"
Console.WriteLine("Enter a number>")
theNumber = Int(Console.ReadLine())
theNumber)
Console.ReadKey() ht
Console.WriteLine("Now " & theWord & " is the word and the number is " &
us
End Sub
End Module
.M
M
Sub Main()
aq
Console.WriteLine("The total is " & total)
Console.ReadKey()
End Sub
End Module
ht
us
Tasks
3.3) Write a program that displays any times table the user requests
M
System.Console.WriteLine("Enter an integer…")
intInput = Val(System.Console.ReadLine())
If intInput = 1 Then
System.Console.WriteLine("Thank you.")
ElseIf intInput = 2 Then
System.Console.WriteLine("That's fine.")
ElseIf intInput = 3 Then
System.Console.WriteLine("Too big.")
aq
Else
System.Console.WriteLine("Not a number I know.")
End If
Console.ReadKey()
ht
1. Write a program to ask the user what 24+9 is. Say “Excellent” if they get it right.
us
2. Write a program to ask the user “how many in a bakers dozen?” and say “most
.M
3. Write a program to ask the user to enter their age. If their age is under 18 then say
“Sorry, this film is not for you”.
4. Write a program to ask the user for two numbers. Compare the first with the second
and then print out one of three messages. Either the numbers are equal, the first is
bigger, or the second is bigger. You will need more than one IF to solve this one.
5. Write a program which asks the user to enter their password. If they enter the word
“PASSWORD” then display the message “Welcome to the treasure”, otherwise
display a message which says “go away, it’s all mine”.
6. Write a program which asks the user to enter a number between 1 and 10. If the
number entered is out with this range then display a message “Sorry…out of range”.
Sub Main()
age = Int(Console.ReadLine())
aq
Console.WriteLine("You are too young to drive")
End If
Console.ReadKey()
End Sub
End Module
ht
us
The symbols we can use to test for conditions are as follows:
== IS Equal To
!= Not Equal To
Sub Main()
aq
Console.WriteLine("You can drive!")
Else
Console.WriteLine("You are not eligable for a driving licence")
End If
Console.ReadKey()
End Sub
ht
us
End Module
.M
M
The heating system in a school should be switched on if the average temperature is less than
17 degrees Celsius (˚C). The average temperature is found from the temperatures in the Art,
English and Music Departments. You are required to write a program that allows the user to
input the three temperatures. The program calculates and displays the average temperature
then displays ‘Heating should be on.’ or ‘Heating should be off.’ as appropriate.
aq
You may practice this task at home, but won’t be able to refer to any notes or files when assessed.
ht
Submit the following for marking in 1 word document:-
Dim a, b, c, d, e, f, g As Boolean
c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11
' The preceding statements set c to True and d to False.
aq
' The preceding statements set e to True, f to False, and g to False.
Dim x, y As Boolean
x = Not 23 > 14
y = Not 23 > 67
ht
' The preceding statements set x to False and y to True.
us
Tasks
rounded = Math.Round(num)
squarert = Math.Sqrt(num)
aq
Console.WriteLine("round: " & rounded & vbNewLine & "Square Root: " & squarert)
trunc = Math.Truncate(num)
ht
Console.WriteLine("The number truncated is " & trunc)
Console.WriteLine("This is not always the same as rounded")
Console.ReadKey()
us
Tasks
.M
1) Write a program that asks for 5 numbers, calculates the mean average and then rounds it
down. Display the result on screen.
M
Console.WriteLine(theString)
aq
Console.WriteLine(theString.Substring(12)) 'displays the substring starting at
position 12
ht
newString = "Speak to Dave! " & theString 'string concatenation
Console.WriteLine(newString)
us
Console.ReadKey() 'pause and wait so user can read output.
.M
Tasks
1. Write a program that checks a username against a stored value. How the user enters the
M
2. Adapt program 1 so that it also takes in a password. If the user enters spaces after the
password the computer will trim them out automatically.
3. Write a program that will check a phone number is of the correct length.
4. Write a program that asks for a user’s full name in one inputbox/textbox but then stores the
first and second names in different variables.
theInt = "23021980"
theReal = "230.21980"
theDate = "23-02-1980"
'whole numbers
Console.WriteLine(theInt)
Console.WriteLine(theInt + "1")
Console.WriteLine(Convert.ToInt32(theInt))
Console.WriteLine((Convert.ToInt32(theInt) + 1))
aq
Console.WriteLine()
'real numbers
Console.WriteLine(theReal)
Console.WriteLine(theReal + "1")
ht
Console.WriteLine(Convert.ToDouble(theReal))
Console.WriteLine(Convert.ToDouble(theReal) + 1)
Console.WriteLine()
us
'dates
Console.WriteLine(theDate)
Console.WriteLine(theDate + "1")
Console.WriteLine(DateTime.Parse(theDate))
.M
Console.WriteLine(DateTime.Parse(theDate).AddDays(1))
Tasks
Module Module1
Sub Main()
theNumber = 7
'a loop
For x = 1 To 10
Console.WriteLine("7 x " & x & " = " & (7 * x))
Next
aq
'the end of the loop
End Sub
End Module
ht
us
Tasks
1. Write a program which asks for your name and then displays it 5 times on the
.M
screen.
2. Write a program to display the name of the town you live in 10 times.
3. Write a program to ask for a person’s favourite CD and the artist. Both should
M
4. Write a program to ask for a number and display its multiplication table 1 to
100
5. Write a program that asks the user for a number 5 times and adds them all up
to give a total.
Section 12 - Flowcharts
aq
ht
Task 12.1 Create a program from the following flowchart:
us
.M
M
aq
ht
us
.M
M
'this is a procedure
Sub timestable(ByRef number As Integer)
For x = 1 To 10
Console.WriteLine(number & " x " & x & " = " & (number * x))
Next
End Sub
aq
End Function
Sub Main()
different data
timestable(9)
ht
timestable(3) 'this is a second call to the same procedure but now with
us
Console.ReadKey()
Console.Clear()
Dim x As Integer
.M
Console.WriteLine("4 + 6 = " & adder(4, 6)) 'you can simply the code by
putting the call directly into the print statement
M
Console.ReadKey()
End Sub
End Module
Tasks
If you want to pass the value of the variable, use the ByVal syntax. By passing the value of the
variable instead of a reference to the variable, any changes to the variable made by code in the
subroutine or function will not be passed back to the main code. This is the default passing
mechanism when you don’t decorate the parameters by using ByVal or ByRef.
If you want to change the value of the variable in the subroutine or function and pass the revised
value back to the main code, use the ByRef syntax. This passes the reference to the variable and
allows its value to be changed and passed back to the main code.
aq
ht
us
.M
M
An example of output is shown below. The output from your program may look different but
must meet the specification.
aq
TERVUREN CAR HIRE COMPANY
ht
Enter car model. Golf
Enter daily rate. 22
6 132
7 154
8 176
9 198
10 220
M
11 242
12 264
13 286
14 308
You may practice this task at home, but won’t be able to refer to any notes or files when assessed.
1
Daily rates are in whole numbers of pounds.
'number constants
Const conPi = 3.14159265358979
Const conMaxPlanets As Integer = 9
'string constants
Const conVersion = "07.10.A"
Const conCodeName = "Enigma"
aq
'to make a constant available to the whole program "Public" should precede it
'and it should be placed inside the module but outside the procedure
'try it
Type VariableType
Variable1 as varType1
Variable2 as varType2
….
VariableN as varTypeN
End Type
aq
After that you can declare any name as this new variable type and use it as ordinary variable.
ht
Note: Special for this project, please do not copy and paste from this tutorial. Type the code
manually so that you may understand the different between UDT and normal variable.
us
Create new console project
Name As String
Population As Long
M
End Type
Sub Main()
Dim myRecord As City
myRecord.Name = Console.Readline()
myRecord.Population = Console.Readline()
myRecord.Year = Console.Readline()
myRecord.Diameter = Console.Readline()
Console.Writeline(myRecord.Name & " city has population of " & _ myRecord.Population & "
million people " & vbCr & " and diameter of " & myRecord.Diameter & " km in year " & _
myRecord.Year
End Sub
Tasks
1) Run the program and try the data for some real city. You see that UDT combine several data
type into single unit.
2) Adapt the program so each input has a suitable prompt
Byte
Bytes are 8-bit (1 byte) unsigned integers ranging in value from 0 to 255 ( 0 to 2^8-1). The You can
declare Byte variables using the BYTE keyword with the DIM statement. For example:
DIM I AS BYTE
Byte variables are particularly useful for storing small, unsigned integral quantities like the number
of days in a month. You should not use Byte variables in FOR/NEXT loops, as they are highly
aq
inefficient.
Enum CardSuit
Clubs
Diamonds ht
us
Hearts
Spades
End Enum
.M
Enum DayOfWeek
Monday = 1
Tuesday = 2
Wednesday = 3
M
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
End Enum
Enum Result
Win = 3
Lose = 1
Draw = 0
End Enum
Records
In VB, Records are known as structures. They allow you to combine several data items (or fields) into
one variable. For example in college instead of having a separate variable to store information about
each fact about a student, you would create a student record with fields to store each fact (or field!):
aq
dim DoB as date 'field
End Structure
Sub Main()
ht
us
dim newStudent as student
newStudent.id = console.readline()
newStudent.name = console.readline()
newStudent.DoB = console.readline()
console.writeline("new record created: " & newStudent.id & " " & newStudent.name & " " &
newStudent.DoB)
End Sub
But why should we use Records? Well it makes for much neater code, without having to declare
dozens of variables, we could declare a couple of students. You'll also see how neat your code can
become when using arrays of records.
Tasks
aq
ht
us
.M
M
countries(1) = "Scotland"
countries(2) = "Belgium"
countries(3) = "Netherlands"
countries(4) = "Germany"
countries(5) = "France"
Randomize()
randomNum = Int(Int((5 * Rnd()) + 1))
aq
Console.ReadKey()
Tasks
ht
us
1) Write a program which will set up an array to hold 50 numbers. Call the array numbers. Display
the array's contents across the screen. They should all be 0.
2) Create a program that stores an array of car records. At least 5 cars and 4 fields per record.
.M
3) Create a program that stores an array of 5 people records. The information should be entered by
the user.
M
4) Adapt program 2 to now do a linear search for a certain car and display it’s details.
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New IO.StreamReader("H:\Diary.txt")
aq
Console.WriteLine(strLine)
Tasks
.M
1) Write a program that reads the students’ names from a txt file and displays them on the
screen
2) Write a program that reads 10 team names from a txt file and stores them in an array
M
3) Write a program that reads 5 song titles from a csv file and displays them on the screen
4) Write a program that reads 20 team names from a csv file into an array, then displays the
array on screen
'Pass the file path and the file name to the StreamWriter constructor.
objStreamWriter = New IO.StreamWriter("H:\Testfile.txt")
aq
Tasks
ht
1) Write a program that asks for 5 names and then writes then to a file
2) Write a program that writes the colours of the rainbow to a csv file
3) Write a program that reads a hiscore table from a file, asks the user to add a new hiscore,
us
then writes this new hiscore table to the file.
.M
M
Module Module1
Structure person
Dim name As String
Dim age As Integer
Dim alive As Boolean
End Structure
aq
Sub Main()
'display data
Console.WriteLine("Student1: " & student1.name & vbTab & student1.age & vbTab
& student1.alive)
Console.WriteLine("Student2: " & student2.name & vbTab & student2.age & vbTab
& student2.alive)
Console.ReadKey()
End Sub
End Module
Tasks
1) Amend the program so that there is a write procedure and a read procedure which are
called
2) Amend the program so that the 2 student are stored in an array of people, then write and
read the array to the file
Do
Console.WriteLine("Enter a mark between 0 and 10")
mark = Val(Console.ReadLine())
If (mark > 10) Or (mark < 0) Then Console.WriteLine("That was not a valid
mark")
Loop Until (mark >= 0) And (mark <= 10) ' keeps going until a valid mark is entered
Console.WriteLine("Well done!")
Console.ReadKey()
aq
Tasks
1) Write a program that validates a user is old enough to drive (older than 17, younger than 80)
ht
2) Write a program that checks that a telephone number entered is long enough (string length)
3) Write a program that checks that both a username and password is correct before allowing
us
you to proceed.
.M
M
aq
For x As Integer = 0 To bound1
' Get element.
Dim s1 As String = values(i, x)
Console.Write(s1)
Console.Write(" "c)
Next
Next
Console.WriteLine()
ht
us
Console.ReadKey()
.M
Tasks
1) Create a 2d array which stores and displays a grid for noughts and crosses. Allow users to
pick a location and set it to an X or a O.
M
2) 2d array which stores a grid for Battleships. Allows the user to place their 5 ships and isplay
on screen.
You might think it would be better to use a String to hold the current value instead, but there are
several reasons why an Enum is better, such as:
• The list of valid options will be shown in a pop-up list when you are writing code (see the
picture below, after the first Code snippet), so you don't need to remember them or even
type them - instead you can just select them with your mouse or keyboard.
• It is harder to make a typo that causes bugs, as not only are the values shown in the list for
aq
you to pick from, but also valid entries you type will be changed to the case you declared
them - so you can see when the case is not automatically corrected for you.
• If you use Option Explicit (which is highly recommended anyway), any typo's will cause a
message warning you about them.
•
ht
They take less memory than Strings, and code that uses them runs faster than the String
equivalent.
us
Enum Importance
Critical = 4
Important = 3
None = 0
.M
Regular = 2
Trivial = 1
End Enum
Sub Main()
M
aq
Next
Console.WriteLine(output.ToString())
Console.ReadKey()
Range
ht
' Generate a sequence of integers from 1 to 10
' and project their squares.
us
Dim squares As IEnumerable(Of Integer) = Enumerable.Range(1,
10).Select(Function(x) x * x)
output.AppendLine(num)
Next
Console.ReadKey()
Intersection
' Create two integer arrays.
Dim id1() As Integer = {44, 26, 92, 30, 71, 38}
Dim id2() As Integer = {39, 59, 83, 47, 26, 4, 30}
Difference (Distinct)
Module Module1
Sub Main()
Dim products() As Product =
{New Product With {.Name = "apple", .Code = 9},
New Product With {.Name = "orange", .Code = 4},
New Product With {.Name = "apple", .Code = 9},
New Product With {.Name = "lemon", .Code = 12}}
aq
Console.WriteLine(product.Name & " " & product.Code)
Next
Console.ReadKey()
End Sub
End Module
ht
us
Public Class Product
Public Property Name As String
Public Property Code As Integer
End Class
.M
ByVal x As Product,
ByVal y As Product
) As Boolean Implements IEqualityComparer(Of Product).Equals
' Check whether the compared objects reference the same data.
If x Is y Then Return True
' Get hash code for the Name field if it is not null.
Dim hashProductName =
If(product.Name Is Nothing, 0, product.Name.GetHashCode())
aq
ht
us
.M
M
Membership (Contains)
' Create an array of strings.
Dim fruits() As String = {"apple", "banana", "mango", "orange",
"passionfruit", "grape"}
aq
Console.WriteLine ("The array " & text & " contain " & fruit)
Console.ReadKey()
ht
us
.M
M
aq
Console.WriteLine("What number do you want to search for?")
Dim searchKey As Integer = Console.ReadLine
Else ht
Console.WriteLine("Found Value in index " & element)
us
Console.WriteLine("Value Not Found")
End If
End Sub
Dim n As Integer
Return -1
End Function ' LinearSearch
Tasks
aq
Dim j As Integer
ht
For j = 0 To UBound(ourArray) - 1
End If
Next
Next
M
Console.ReadLine()
End Sub
Tasks
http://howtostartprogramming.com/vb-net/vb-net-tutorial-2-hello-world/
Form Properties
http://howtostartprogramming.com/vb-net/vb-net-tutorial-6-form-properties/
Progress Bar
http://howtostartprogramming.com/vb-net/vb-net-tutorial-7-progress-bar/
aq
Menu Strip
http://howtostartprogramming.com/vb-net/vb-net-tutorial-10-menu-strip/
ht
http://howtostartprogramming.com/vb-net/vb-net-tutorial-20-advanced-messagebox/
us
Web Browser
http://howtostartprogramming.com/vb-net/vb-net-tutorial-31-web-browser/
.M
Try Catch
http://howtostartprogramming.com/vb-net/vb-net-tutorial-38-try-catch/
M
3) Create a program that codes a string into its ASCII codes and back
aq
6) Create a program that subtracts binary numbers
7) Create a program that converts a decimal number to floating point and back.
ht
8) Create a program that displays a number of bits as bytes, kilobytes, megabytes…..terabytes
aq
ht
us
.M
M
aq
2-program to input(y/n),the program diplays u enterend Y or n,program terminates when user enters
“exit”
ht
us
.M
M
4-write a program to pick any number between 1-6, program terminates when 5 is entered. (Lucky
aq
number game)
ht
us
.M
M
aq
ht
us
.M
M
aq
8-write a program to input some marks then print “admission granted”if avg is greater than 80 else “try
again”
ht
us
.M
M
aq
10-write a program to input 5 temperatures. Validate the input so that a value between 10 to 50 should
be accepted. ht
us
.M
M
aq
12-write a program that inputs code for movie type and displays its category.e.g
S-science fiction movies. Print error message if not within the list.
ht
us
.M
M
aq
ht
us
.M
M
aq
15-write a program to print the table of a number which is input by user.
ht
us
.M
M
18- Write a program to input marks of a class of 5 students re-enter marks if it is out of range e.g. less
than 0 or greater than 100 and display the avg marks.
aq
ht
us
.M
19-Temperatures (°C) are being collected in an experiment every hour over a 20 hour period.
Write an algorithm, using pseudocode or otherwise, which inputs each temperature and outputs
how many of the temperatures were above 20°C
how many of the temperatures were below 10°C
M
aq
Write a program to find the greater number when user enters two numbers. Use functions
ht
us
.M
M
aq
ht
us
Two dimensional arrays
.M
M
Validation
aq
Write a program to input a number between 0-10,if number is in correct range then print “well done “if
it is out of range, you will have to re-input number until correct number is entered
ht
us
.M
M
aq
ht
us
.M
M
aq
ht
Use of Asc() function which Returns an Integer representing the ASCII character
us
code corresponding to the first letter in a string.
.M
M
The Trim () function trims the empty spaces on both side of the phrase.
The left() function extracts the left portion and right() function extracts the right
portion of a string
aq
ht
us
.M
M