Fundamentals of Programming Without Restriction
Fundamentals of Programming Without Restriction
These lines of code will tell the computer what to do, currently they do very little and we need to get
started:
Tradition has it that the first program a programmer should write is "Hello World!". Write the following
sourcecode into a command line VB.NET programming environment:
module module1
sub main()
console.writeline("Hello World!")
console.readline() end sub
end module
If you are using Visual Studio then you can make the program run by pressing F5 or hitting the Run button
that looks a little like this:
You should get the following output:
There it is, you're on your way to becoming a programmer! There is a lot more to learn and over the course
of the next few sections you'll get a crash course in programming.
First of all let's look at another program and find out what it's doing:
1. module module1
2.
sub main()
3.
console.writeline("Hello there, my name is Peter and my age is 29")
4.
console.writeline("6 * 6 = " & 6 * 6)
5.
console.readline()
6.
end sub
7. end module
Page 1
But wait a second, this program isn't much use! Your name probably isn't Peter and you're even less likely
to be 29. Time for you to write some code yourself:
Page 2
Answer :
1. module module1
2. sub main()
3. console.writeline("Dear Teacher,")
4. console.writeline("My name is Dave and this homework is too easy.")
5. console.writeline("2 + 2 = " & 2 + 2) 'bonus points for using a sum!
6. console.writeline("")
7. console.writeline("Yours Sincerely,")
8. console.writeline("Dave")
9. console.readline()
10. end sub
11. end modul
Page 3
Page 4
What you have just seen is a declaration of two variables, name and age. A variable is a known or
unknown value that has been given a symbolic name. This allows the name to be used independently of the
Fawad Khan 0321-6386013
Page 5
value. It is advisable that a meaningful name for readability and convenience. This name is known as the
identifier. To declare a variable in VB.NET we do the following:
Dim identifierName As datatype
Variable - short term memory used to store temporary values in programming code
Once you have declared a variable you need to assign it a value. Assignment, in programming terms, is the
giving of a value to a variable, for example:
identifierName = 7
Here we are assigning the value 7 to the variable identifierName, so when we use identifierName, we
mean the value 7:
1.
2.
3.
Exercise: Variables
Update the code above to display the age in days, hours, minutes and seconds. No use of calculators! Use
the code to do all the work for you.
Answer:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Page 6
Answer:
To keep track of a changing value that is used in many places but only needs to be updated in one.
What will the following code output:
1.
2.
3.
4.
5.
6.
7.
dim x, y as integer
x = 45
y=9
console.writeline("The sum of x + y = " & x + y)
console.writeline("y goes into x " & x / y & " times")
console.writeline("x times y = " & x * y & " times")
console.readline()
Page 7
Another use for comments is to disable code that you don't want to delete but you do want to keep. By
commenting out the code it means that you can always restore it later if you want to. It isn't a good idea to
leave commented out code in final code, but it is a very common practice when you are developing
something:
'the code below now only takes one name as input instead of three
dim a as string ' declare variables to store names
', b, c as string ' this code does nothing!
'''' read the three names ''''
a = console.readline()
' b = console.readline()
' c = console.readline()
console.writeline("the names are :" & a)
' & b & c)
Page 8
Page 9
Up should pop some suggestions. Play around with BackgroundColor and ForegroundColor
There is also a command to output a small and annoying sound, it's unlikely you'll need to know
this for the exam, and your teachers will most likely hate it.
console.beep() 'plain beep
console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds
Page 10
Inputs
To make your program interactive you'll need your user to input commands, for the exam these will most
likely be text instructions or reading from a file (covered later). You might look at buttons and games
controllers next year. In VB.NET there are two types of input command that you need to know:
variable1 = console.readline() 'reads input until user presses enter and stores it in variable1
variable2 = console.read() 'reads one key press/character and stores the ASCII code in variable2. We'll
learn more about this later
Let's take a look at a quick example of where this might be used:
dim name as string 'declare a variable called name
console.write("Please insert your name:") ' write "Hello" and the name to the screen
name = console.readline() 'assign the user's input into the variable name
console.writeline("Hello " & name) ' write "Hello" and the name to the screen
There is also the console.ReadKey()command that reads in a single character. Take a look at this example:
dim urChoice as char 'declare the name
console.writeline("Please select from options 1,2,3 or 4:")
urChoice = console.Readline() 'read the users input into the variable name
console.writeline("You chose : " & urChoice )
Page 11
Answer:
console.writeline("My favourite colours:")
console.writeline("Red")
console.writeline("Blue")
Page 12
Page 13
Addition
Subtraction
Multiplication
Division
Integer division
Remainder Division
Exponentiation
String concatenation
7 + 2
7 - 2
7 * 2
7 / 2
7 \ 2
7 Mod 2
7 ^ 2
"7" & "7"
produces
produces
produces
produces
produces
produces
produces
produces
9
5
14
3.5
3
1
49
"77"
Let's look at a short example of arithmetic operations before we jump into the operators themselves.
In this example we will also be using some basic variables. The Dim operator creates the variable.
1.Dim Commission As Single
2.Dim Sales As Single
3.Sales = 3142.51
4.Commission = 0.3 * Sales ' Calculate 30% commission.
First, we set the total Sales to 3142.51.
The * operator calculates multiplication, so line 4 is equivalent to multiplying 0.3 and Sales
together. Sales is 3142.51, so our result should be the product of 0.3 and 3142.51, and stored in
Commission.
Why the funny symbols?
With the exception of addition and subtraction, the symbols used are different to the ones used in real life.
This is simply because the other symbols are not available on a standard keyboard (try and find m on
yours!) or the symbol is in the alphabet and can be used for naming a variable (x).
Page 14
Addition
This adds two numbers together, and is denoted by the "+" symbol. If strings are involved it may also do
String concatenation, that means sticking the two strings together. Examples:
x = 7 + 2 ' Results in 9.
x = 25 + -4 ' Results in 21.
Dim StringA As String
StringA = "A string" + "Another string" ' Results in "A stringAnother string"
There is a second addition operator, "+=". It increments the variable on the left of the += by the amount
indicated on the right.
Dim x As Integer = 54
x += 89
' result is 143
x += 7
' result is 150
It also works with Strings as a concatenation operator.
Dim x As String = "A fox"
x += " jumped"
' result is "A fox jumped"
x += " over the fence" ' result is "A fox jumped over the fence"
Subtraction
This subtracts two numbers, and is denoted by the "-" symbol. Examples:
Dim x As Integer
x = 7 - 2 ' Results in 5.
x = 25 - -4 ' Results in 29.
Multiplication
This multiplies two numbers, and is denoted by the "*" symbol. Examples:
Dim x As Integer
x = 7 * 2 ' Results in 14.
x = 25 * -4 ' Results in -100.
Division
There are more types of division than the one denoted by the "/" symbol. There is also integer division and
remainder division.
Page 15
Normal
This is the most commonly used form of division and is denoted by the "/" operator. Examples:
Dim x As Single
' (note that we must use the Single class to have decimals)
x = 7 / 2 ' Results in 3.5.
x = 25 / 4 ' Results in 6.25.
Integer division
This divides two numbers, and gives the result without the remainder if the quotient is a decimal.
Examples:
Dim x As Integer
x = 7 \ 2 ' Results in 3.
x = 25 \ 4 ' Results in 6.
Remainder Division
This divides two numbers, and gives the result's remainder if the quotient is a decimal. This is denoted by
the operator "Mod." Examples:
Dim x As Integer
x = 7 Mod 2 ' Results in 1.
x = 25 Mod 4 ' Results in 1.
Exponentiation
This is raising a number to a power. For example 72 in VB .Net code is:
Dim x As Integer
x = 7 ^ 2 ' Results in 49.
This results in the number 49 being assigned to the variable x. It can also be used to calculate the square
root of a number. The square root of a number is the number raised to the power of 0.5.
Dim x As Single
x = 7 ^ 0.5 ' Results in a number around 2.645.
Page 16
Using these data types we can start to write a simple computer program:
dim name as string
dim age as integer
name = "Barry"
age = 56.3
Console.writeline("hello " & name & "! you are " & age & " years old")
I told it that Barry was 56.3 years old! The reason is because I have used an integer to store the age and
not a real (single or double) datatype, it therefore drops the decimal part. Integers, afterall, don't store
decimal places!
Assignments
Depending on the datatype, we assign values in different ways:
Fawad Khan 0321-6386013
Page 17
Integers, Bytes, Real, Singles, Doubles = Plain assignment without speech marks
exampleNumber = 7.65
Age
Name
Gender
Height(metres)
Date of Birth
license (Do they have a driver license)
Answer :
dim age as integer
dim name as string
dim gender as char 'OR dim gender as string
dim height as decimal
dim DoB as date
dim license as boolean
Write assignment statements for the following variables using yourself as an example:
Name
Age
Gender
Answer :
name = "Peter" 'we must use speech marks for text, so we don't mistake the value for a variable
age = 56 'we don't need speech marks for numbers
gender = "m"
Which of the following declarations correct, which are wrong and why?
dim colour as string
Page 18
Answer:
dim colour as string 'CORRECT, also we could use a single to store the frequency
dim wheelNum as integer 'CORRECT
dim topSpeed as single 'WRONG, we don't need such precision, an integer would do
dim hasElectricWindows as char 'WRONG, a boolean would work better
Which of the following assignments are correct, which are wrong and why:
name = Pete
age = "34"
height = twenty
electricWindow = True
Answer:
name = Pete 'WRONG, we're assigning a string so we need to use speech marks
name = "Pete"
age = "34" 'WRONG, we're assigning an integer so we don't need speech marks
age = 34
height = "twenty" 'WRONG, height is numeric, so we need to assign a number without speech marks
height = 20
hasElectricWindow = True 'CORRECT assuming you made the change from the previous question
Answer:
Write code that asks the user to insert three numbers with decimals, then outputs them (1) all multiplied together,
and (2) added together. For example:
Page 19
Answer:
dim num1, num2, num3 as single 'NOT integer, we need decimal numbers! You can use different identifiers
console.write("Please insert number 1:")
num1 = console.readline()
console.write("Please insert number 2:")
num2 = console.readline()
console.write("Please insert number 3:")
num3 = console.readline()
console.writeline("multiplied together = " & num1 * num2 * num3)
console.writeline("added together = " & num1 * num2 * num3)
console.readline()
Page 20
If you try to change a constant value it will bring up an error. They are very useful for values that do not
change or rarely change such as VAT, pi, e, etc. By using a constant you don't run the risk that you might
accidentally change the value, you wouldn't want to accidentally change pi to equal 4 as All your
calculations would go wrong!
Exercise: Constants
Write a program that works out the area and circumference of a circle, setting pi to a constant. Use the
equations: area = r2 and circumference = 2r For example:
Answer:
1.
2.
3.
4.
5.
6.
7.
Page 21
Answer:
1.
2.
3.
4.
5.
6.
7.
8.
9.
Why might you want to use a constant in your code instead of a normal variable?
Answer:
Constants are fixed values, so you can't accidentally assign them new values in other parts of your code
When is it suitable to use a constant?
Answer:
When you are using a value that doesn't need to change at run time and will be used in more than one
location.
Page 22
The most common selection statement is the IF statement, the idea is that you compare a value to some
criteria, IF the value and criteria match then you proceed in a certain way, otherwise you do something
else. For example:
If It is the queen Then
Salute her
Else
Treat them like a commoner
End
If name = "Queen" Then
console.writeline("Hello your Majesty")
Else
console.writeline("Get to the back of the queue!")
End If
The Else part is optional, you can just ignore the commoner! (and dump the Else)
If name = "Queen" Then
console.writeline("Hello your Majesty")
End If
You might also want to test multiple things in the If statement. For example:
If name = "Queen" And age >= 18 Then
console.writeline("Hello your Majesty, I can serve you beer")
Else
console.writeline("Get out of my bar!")
End If
Page 23
Exercise: IF statements
Write a single IF statement for the following:
Ask a user for their eye colour, if they say green call them a "Goblin", else they must be a different type of
monster:
Answer :
dim eyes as string
console.writeline("What eyes have thee?")
eyes = console.readline()
If eyes = "Green" Then
console.writeline("Thou art a Goblin?")
Else
console.writeline("Pray tell, be thou another form of beast?")
End If
Try the code by inputting "green". It doesn't work! We need to adjust the IF statement: If eyes = "Green" or
eyes = "green" Then 'the Or part makes sure it picks up upper and lower case letters alternatively we could
use UCase() we'll find out more about this later If UCase(eyes) = "GREEN" Then 'UCase converts the entire
input into capitals </syntaxhighlight>
Page 24
Using one IF statement write code to handle the above. HINT: you might need more than one clause in
the IF ... THEN section.
Answer:
dim age as single
console.writeline("How old are you:")
age = console.readline()
If age >= 11 And age < 17 Then
console.writeline("You're probably at secondary school")
Else
console.writeline("You're not at secondary school")
End If
Page 25
Nested Ifs
Sometimes when we are trying to write complex code we will need to use a combination of IFs. In the
example above we might want to still treat an under-age queen with respect, an under-age commoner
with contempt, serve an 18+ queen with respect, and serve an 18+ commoner with common manners. In
fact it seems as if we need 4 different IF statements. We could solve it like this:
If name = "Queen" And age >= 18 Then
console.writeline("Hello your Majesty, may one serve you beer?")
End If
If name = "Queen" And age < 18 Then
console.writeline("I'm sorry your Majesty, you are too young to buy beer")
End If
If name <> "Queen" And age >= 18 Then '<> means not equal (so does !=)
console.writeline("Hello mate, can I serve you beer?")
End If
If name <> "Queen" And age < 18 Then
console.writeline("Get out of my pub, you are too young to buy beer")
End If
This seems awfully cumbersome and we will now look a more elegant way of solving this, using Nested
IF's. First of all, nested means placing one thing inside another, so we are going to place an IF inside
another.
If name = "Queen" Then
If age < 18 Then
console.writeline("I'm sorry your Majesty, you are too young to buy beer")
Else
console.writeline("Hello your Majesty, may one serve you beer?")
End If
Else
If age >= 18 Then
console.writeline("Hello mate, can I serve you beer?")
Else
console.writeline("Get out of my pub, you are too young to buy beer")
Page 26
End If
Try the examples above with the following data, both solutions should provide the same answer:
name = "Queen" age = 18
name = "Quentin" age = 28
name = "Queen" age = 17
name = "Aashia" age = 15
Page 27
Answer:
dim age as integer
dim drinking as string
console.writeline("How old are you?")
age = console.readline()
if age >= 21 then
console.writeline("Good, that's old enough. Have you been drinking?")
drinking = console.readline()
if drinking = "Yes" then
console.writeline("Come back tomorrow")
else
console.writeline("Your carriage awaits")
end if
else
console.writeline("You're too young I'm afraid. Come back in a few years")
end if
Page 28
If they get the username wrong it should immediately kick them out and not ask for the password. If they get the
password wrong it should kick them out.
Answer:
dim name as string
dim password as string
console.writeline("Enter username:")
name = console.readline()
if name = "Jonny5" then
console.writeline("RECOGNISED! Enter password:")
password = console.readline()
if password = "Alive" then
console.writeline("Please enter " & name)
else
console.writeline("INCORRECT! Get out!")
end if
else
console.writeline("Username not recognised. Get out!")
end if
Page 29
But be careful, code like this can often be harder to read and therefore debug. Once it has been through
the interpreter / compiler it almost certainly won't be running any faster either, it's just there for you to
save a little space. For the exam keep to the longer version.
Page 30
Case Statement
The other type is the Case statement, this can be summarised by several if statements where the value is
compared to several criteria and the action of first criteria matched is performed, otherwise a default action
may be performed.
Case Enter Restaurant and pick up menu
If Egg and Chips available Then
Order Egg and Chips
End If
If Pie and Chips available Then
Order Pie and Chips
End If
If Curry and Chips available Then
Order Curry and Chips
End If
If Pizza and Chips available Then
Order Pizza and Chips
End If
Default
Leave hungry
End
Page 31
However, most programming languages will give you a shortened way of implementing a case statement
without the need to write all of these if statements. For example in VB.NET we use the select case
Dim number As Integer = 5
Select Case number
Case 1, 2, 3
Console.WriteLine("Between 1, 2, 3 inclusive")
Case 4 to 8
Console.WriteLine("Between 4 and up to 8")
'This is the only case that is true
Case 9
Console.WriteLine("Equal to 9")
Case 10
Console.WriteLine("Equal to 10")
Case Else
Console.WriteLine("Not between 1 and up to 10")
End Select
Pig - Oink
Cow - Moo
Bear - Grr
Sheep - Baa
Tiger - Grr
everything else - Meow
Page 32
You are now going to use a case statement to create an electronic piano.
Note Frequency
A
220.00
B
246.94
C
261.63
D
293.66
E
329.63
F
349.23
G
392.00
Create a case statement in the code below, that will play the notes written above. The while true loop
means that the code will never end and will continue for ever. For bonus points try and get the code to
accept both upper and lower case inputs
'instruction statement here
While True
'input and case statements here
While End
Page 33
Answer:
dim note as char
console.writeline("please insert a musical note:")
While True
note = Console.ReadKey().KeyChar
'note = Console.Readline() 'also works, but it less fun
Select Case UCase(note)
Case "A"
Console.Beep(220,50)
Case "B"
Console.Beep(247,50)
Case "C"
Console.Beep(262,50)
Case "D"
Console.Beep(294,50)
Case "E"
Console.Beep(330,50)
Case "F"
Console.Beep(349,50)
Case "G"
Console.Beep(392,50)
End Select
End While
Page 34
A computer game example would be increasing the speed of a car while the accelerator is pressed down
and until you hit its top speed.
dim maxSpeed as integer = 120
dim curSpeed as integer = 0
dim pedalPress as boolean = True
While curSpeed <= maxSpeed And pedalPress = True
console.writeline(curSpeed)
curSpeed = curSpeed + 1
End While
console.writeline("MAXSPEED!")
Page 35
Answer:
dim count as integer = 20
While count <= 60
console.writeline(count)
count = count + 1
End While
Write a program that takes an input and outputs the times table for that number:
Answer:
dim count as integer = 1
dim times as integer
console.write("insert a number: ")
times = console.readline()
While count <= 10
Page 36
Write a program that adds all the numbers from 10 to 20 inclusive together and finally outputs the result
Answer:
dim count as integer = 10
dim total as integer = 0
While count <= 20
total = total + count
count = count + 1
End While
console.writeline("the total is: " & total)
While Do
Page 37
Do While Loop
Another type of while loop is a Do-While loop. This is slightly different from the While loop in that you
perform the task before you check that you have to perform the task again. This means you perform the
task whatever the circumstances of the check:
Do
increase speed
While not top speed
End
Page 38
Page 39
Answer:
console.write("how old are you?")
age = console.readline()
While age < 17
console.writeline(age & " year olds should attend school!")
age = age + 1
End While
console.writeline(age & " is too old to attend school!")
For Loop
The most complicated tool you may meet is the for loop. This is a glorified While loop and don't be put off
by how complicated it looks. It also tends to be one of the easiest ways to iterate in Visual Basic
For (speed = 0, not top speed, increase speed)
drive
Page 40
Page 41
Write code that will input a lower and higher number, then write the numbers on the screen, starting at
the lower and writing each number until you reach the higher. Use a for loop, it should display the
following:
Answer :
dim lower, higher as integer
console.write("insert lower number: ")
lower = console.readline()
console.write("insert higher number: ")
higher = console.readline()
For x = lower to higher
console.writeline(x)
Next
Write a for loop that will output the frequencies: 100,200,300,400, ... , 20000. HINT, you might want to
start at 1 and multiply. Remember console.beep(200, 200)
Answer:
For x = 1 to 200
console.beep(x* 100, 100)
Next
Page 42
Get the computer to keep asking a user whether they are "Ready to launch?". If they say anything other
than "Yes", then keep asking the question. If they say yes, then count down from 5 and end with the
words "BLAST OFF!".
Extension: If you want to really show that you know how to use case statements, get it to say: FIVE, FOUR,
THREE, TWO, ONE instead of showing the numbers
Answer:
Dim answer As String
Do
Console.Write("Ready to launch? ")
answer = Console.ReadLine()
Loop While answer <> "Yes"
For x = 5 To 1 Step -1
Console.WriteLine(x)
Next
Console.Write("BLAST OFF!")
Page 43
The round function is used to round numbers to a limited number of decimal places using the Math.Round()
function
Truncation
The truncate function returns the integer part of a number, regardless of the decimal places.
Math.Truncate(19.45) 'Returns 19
Math.Truncate(19.9999) 'Returns 19
This is particularly useful when you are trying to perform DIV in modular arithmetic.
The above code will give you a random number between 1 and 2,147,483,647. You might well require a
number that is a little smaller. To get a random number between two set numbers, in this case 5 and 10
you can use the following:
randomNumber = rndGen.Next(5,10)
So how exactly can we use this? Take a look at the following game:
Dim rndGen As New Random()
Dim randomNumber As Integer
Page 44
Adjust the code above to tell the user how many guesses they took to find the random number. HINT:
you'll need a variable
Answer:
Sub Main()
Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess As Integer
Dim count As Integer = 1
randomNumber = rndGen.Next(1, 100)
Console.WriteLine("Please guess the random number between 1 and 100")
Do
Console.Write("your guess:")
guess = Console.ReadLine()
If guess > randomNumber Then
Console.WriteLine("Too High")
End If
If guess < randomNumber Then
Console.WriteLine("Too Low")
End If
If guess <> randomNumber Then
count = count + 1
End If
If guess = randomNumber Then
Console.WriteLine("Well done, you took " & count & " guesses to find it!")
End If
Loop
End Sub
Page 45
Answer:
Write some code to output the integer part of a number input by the user
Answer:
Math.Truncate(input)
Write code to output the integer and decimal parts of an input number:
Answer:
dim num as single
console.write("Please insert a decimal number: ")
num = console.readline()
console.writeline("The whole number part of this number is: " & Math.Truncate(num))
console.writeline("The decimal part is: " & num - Math.Truncate(num))
Page 46
Position
This function allows us to find the position of an item within a given string and returns the position's
location. In visual basic this is performed by the following command: InStr([string], [item]) For example we
might want to find the location of an end of a sentence by looking for a fullstop:
someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))
We can also use this command to search for strings within strings. For example if we were to look for to
see if a sentence contained a certain name:
someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))
Page 47
If the search item is not contained in the string then it will return 0
someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))
Substring
This function allows you to snip items out of a string and return a substring. Visual Basic uses the
following command: [string].Substring([startPosition],[lengthOfReturnString]). For example we might
want to find the local number from a landline phone number we have been given. We'll have to ignore
the area code:
phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)
Concatenation
This function allows you to stick strings together (concatenate) so that you can start to build strings using
variables. Visual Basic uses the following command: [stringA & stringB] For example we might have a
users name stored in a variable dim name as string and a greeting that we would like to give them:
name = "Charles"
console.writeline("Hello " & name & ". How are you today?")
Page 48
This might seem OK, but in other lanuages we might run into trouble. To perform this we would have to
convert from one datatype to another:
dim age as decimal
age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)
Page 49
Answer:
Dim name As String
console.write("Input: ")
name = console.readline()
console.writeline("Hello " & name & " you have " & Len(name) & " letters in your name.")
Some people have stupidly typed their firstname and their surname into a database, write some code
to display the first name, then their surname
dim fistname as string = "Elizabeth Sheerin"
Answer:
Dim name As String = "Elizabeth Sheerin"
Dim firstname, secondname As String
Dim space, textlength As Integer
space = InStr(name, " ")
textlength = Len(name)
firstname = name.Substring(0, space)
secondname = name.Substring(space, textlength - space)
Console.WriteLine("first name is: " & firstname)
Console.WriteLine("second name is: " & secondname)
Page 50
Answer:
Dim phonenum As String = "(01234)567890"
Dim firstbracket, secondbracket As String
Dim textlength, arealength As Integer
firstbracket = InStr(phonenum, "(")
secondbracket = InStr(phonenum, ")")
textlength = Len(phonenum)
arealength = secondbracket - firstbracket
Console.Write(phonenum.Substring(firstbracket, arealength - 1) & phonenum.Substring(secondbracket, textlength secondbracket))
A similar question to the one above, telephone numbers are currently stored in a very unreadable
format: 01234567890, completely missing off the area code. Can you convert them to display the first 5
figures are the area code:
dim phonenum as string = "01234567890"
This should then be output as:
Answer:
Dim phonenum As String = "01234567890"
Console.Write("(" & phonenum.Substring(0, 5) & ")" & phonenum.Substring(6, 5))
Console.ReadLine()
A palindrome is a word, phrase or number that may be read the same way in either direction. For
example 1234321, RACECAR, TOOT and NUN. You need to write a program that checks to see if any
input given is a palindrome and let the user know:
Page 51
Answer:
Dim name As String
Dim length As Integer
Dim Pal As Boolean = TRUE
console.write("Input: ")
name = console.readline()
length = Len(name)
For x = 0 to (length / 2)
If name.Substring(x, 1) != name.Substring(length - x, 1) then
Pal = FALSE
End If
Next
If Pal then
console.writeline("That is a palindrome!")
Else
console.writeline("That is NOT a palindrome!")
End If
Page 52
You can also declare arrays by placing the values directly into them, this code does exactly the same as
the above:
Dim friends() As String = {"Barry", "Aubrey", "Gertrude"}
Page 53
You can treat indexed array items as variables and change their values:
friends(0) = console.readline()
Declare an array listing 5 animals in a zoo (aardvark, bear, cuckoo, deer, elephant) in alphabetical
order:
Answer:
dim zooanimals() as string = {"aardvark","bear","cow","deer","elephant"}
Answer:
console.writeline(zooanimals(0))
console.writeline(zooanimals(4))
Answer :
console.write("Insert new third animal:")
zooanimals(2) = console.readline()
console.writeline("1: " & zooanimals(0))
console.writeline("2: " & zooanimals(1))
console.writeline("3: " & zooanimals(2))
console.writeline("4: " & zooanimals(3))
console.writeline("5: " & zooanimals(4))
''Alternatively an A-grade student might write:
for x = 0 to 4
console.writeline(x + 1 & ": " & zooanimals(x))
next
To print out the entire array it is best to use some form of iteration:
For x As Integer = 0 To 2
Console.WriteLine(friends(x))
Page 54
Page 55
Declare an array that will hold the names of your 5 best friends, call is befr
Answer:
dim befr(5) as string 'befr(4) would also be accepted
Write a loop so that you can input each of your five best friends and it will output them in the order
you input them. For example:
Answer:
dim befr(5) as string
console.writeline("Insert best friends:")
for x = 1 to 5
console.write(x & ": ")
befr(x) = Console.ReadLine()
next
console.writeline("You listed:")
for x = 1 to 5
console.write(befr(x) & ", ")
next
Page 56
Adjust the code above so that it outputs the list in reverse order:
Answer :
dim befr(5) as string
console.writeline("Insert best friends:")
for x = 1 to 5
console.write(x & ": ")
befr(x) = Console.ReadLine()
next
console.writeline("You listed:")
for x = 5 to 1 step -1
console.write(befr(x))
next
Page 57
To save you rewriting lots of code again and again you might use a sub routine, there are two types:
Procedures and Functions. For example in a program you wanted to know today's date, instead of having
to write a separate sub routine to calculate the date each time you wanted to work it out, you would
probably use date(). This is a function, when you call it, it returns a value. It was written by someone else
and you can keep reusing it as many times as you want. Any program written in industry will use sub
routines calling things like:console.writeline(), printScore(), deleteRecord() . Procedures and Functions
allow for you to:
Reuse code
An easy way to tell the difference between a Procedure and a Function is to look at the names:
Functions are fun: if you would call them, they would return a value'
Procedures aren't fun: if you call them they don't return any value. (these are known as sub in Visual
Basic)
Declarations
In VB.NET you declare a procedure by using the Sub command, so where you see Sub below, please read
as Procedure
Declarations are where you state the name of your procedure/function and the code that you want to
execute. Even if you declare a procedure/function, it doesn't mean that the code will run, you need
a Call to actually get the code to execute.
Sub printNumber()
console.writeline(number1)
End Sub
Functions are slightly different, as they return values you must include a return function in their
declaration. And you must specify the datatype of the value being returned, in the case below that is an
Inteteger specified by: ..) as Integer
Function printNumber() as Integer
return number1
Fawad Khan 0321-6386013
Page 58
End Function
Calls
Calls allow you to run the code declared in a procedure/function. You can build up all sorts of
programming structures by making Calls part of the code. Remember that Functions are fun, so you
should be doing something with the returned value.
printNumber() ' a procedure call
console.writeline(printNumber()) ' a function call
dim x = MaximumSpeed() ' another function call
Parameters
Parameters allow you to pass values to the procedures and functions that you declare, you can pass all
sorts of datatypes as parameters and you can pass as many as you like
'declaration
Sub printNumber(number1 as integer) 'one parameter
console.writeline(number1)
End Sub
'...
'call
printNumber(4)
The output would be:
'declaration
Sub printNameAge(name as string, age as integer) 'two parameters
console.writeline(name & " is " & age & " years old")
End Sub
'...
'call
printNameAge("Mounir", 17)
The output would be:
Page 59
'declaration
function squareNumber(number1 as integer) as integer 'one parameter
return (number1 * number1)
End Function
'...
'call
console.writeline(squareNumber(4))
Note that as it's a function, we had to include the call in an equation. It returns a value, it can't sit on its
own. The output would be:
Why would you use subroutines (functions and procedures) in your code?
Answer:
They allow you to create a common routine once and re-use as many times as you want
They allow you to test sub routines independently of the rest of the code
Write a function declaration with the identifier of Avg that will accept 3 numbers (num1, num2, num3)
and return the average:
Answer:
Function Avg(num1, num2, num3)
return (num1 + num2 + num3) / 3
Fawad Khan 0321-6386013
Page 60
End Function
For the above function, write code with a function call to work out the average of three numbers input by
a user:
Answer:
dim a, b, c as integer
console.write("input num1 = ")
a = console.readline()
console.write("input num2 = ")
b = console.readline()
console.write("input num3 = ")
c = console.readline()
console.write("Average = " & Avg(a,b,c))
the identifier
Page 61
Answer :
identifier = nameTimes
nameTimes("Kane",5)
Page 62
ByRef
The parameter that you are passing to a procedure or function is referred to. That means you are pointing
at it, you are going to directly change its value and anything that happens to it within the procedure or
function will change the original value.
Dim number1 as integer = 123
Sub Main()
console.writeline(number1)
IncPrintNumber(number1)
console.writeline(number1)
End Sub
Sub IncPrintNumber(ByRef num as integer)
num = num + 1
console.writeline(num)
End Sub
The output would be:
Page 63
ByVal
The parameter that you are passing to a procedure or function is copied. That means you are taking a
copy of the original value put into the procedure or function call. Anything that happens to it within the
procedure or function will NOT change the original value.
Dim number1 as integer = 123
Sub Main()
console.writeline(number1)
IncPrintNumber(number1)
console.writeline(number1)
End Sub
Sub IncPrintNumber(ByVal num as integer)
num = num + 1
console.writeline(num)
End Sub
This saves a local variable of the number1 value, storing it in num, it is only valid inside the
IncPrintNumber sub routine The output would be:
Page 64
Page 65
What is the difference between a parameter passed by Value and a parameter passed by Reference?
Answer:
A parameter passed by value copies the value of the parameter passed into the sub routine. Any changes
made to this value do not impact on the original value.
A parameter passed by Reference passes a link to a variable. Any changes made to the parameter in the
sub routine change the original variable.
Page 66
It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to
follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running
even if you no longer need/use it.
Local variable - declared within subroutines or programming blocks, their local scope means they can only be used
within the subroutine or program block they were declared in
Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is
called, and once the function ends, the memory taken up by the variable is released. This contrasts with global
variables which do not release memory.
Take a look at this example:
Module Glocals
Dim number1 as integer = 123
Sub Main()
console.writeline(number1)
printLocalNumber()
printGlobalNumber()
End Sub
Sub printLocalNumber
Dim number1 as integer = 234
console.writeline(number1)
End Sub
Sub printGlobalNumber
console.writeline(number1)
End Sub
End Module
Page 67
Why is this? Well we seem to have two versions of the variable number1.
The first version is declared on line 2, this isn't declared inside any sub routines so the variable has
Global scope
The second version is declared inside the printLocalNumber sub routine. As it is declared inside a sub
routine it is only able to be used inside this subroutine. And on line 12 when we
use:console.writeline(number1) it prints out the local variable
So looking at the code inside the main sub routine we have 3 different ways of printing out the variable
number1.
1. Line 5. console.writeline(number1):This uses the global value of number1, as it is inside a sub
routine with no other local declarations
2. Line 6. printLocalNumber():This is calling on the subroutine printLocalNumber() which has a local
variable number1 contained within it on line 11, therefore it uses the number1 value declared on
line 11.
3. Line 7. printGlobalNumber():This is calling on the subroutine printGlobalNumber() which has no
local variable for number1, therefore it uses the global value for number1
Page 68
Rules of thumb: If you want to quickly tell the difference between a global and a local variable use these
quick rules. But be warned they might try to trick you!
If the declaration is indented from the left hand boundary it probably meets one of the above criteria
and is local
If it meets none of the above statements and is declared in the main body of code it is a global
variable
Example Questions
What is the difference between a global and a local variable?
Answer:
Global variables are accessible from all parts of a program, whilst local variables are only accessible within
a programming construct such as a loop, function or procedure
Why is it a good idea to use local variables instead of global variable?
Answer:
Local variables release memory when you have finished with them, global variables are always stored in
memory whether you need them or not
In what situation might you want to use a global variable?
Answer:
When you want to declare a variable that needs to be accessible by all parts of your code
Page 69
Answer:
Locals: age, d
Globals: months
Page 70
For the above code how could you make the code more efficient, and why would it be more efficient?
Answer:
Make the months variable a local variable by putting it inside the printMonths(a) sub routine, if you
leave it as a global variable it will be taking up memory even when you don't need it.
List the Global and Local variables in the following code, list the output:
1. Module greetings
2.
3. Dim q as integer = 6
4.
5. Sub sayGoodbye()
6.
7.
for y = 1 to q
8.
9.
console.write("bye,")
10.
11.
loop
12.
13.
End Sub
14.
15.
Sub sayHello()
16.
17.
dim q as integer = 4
18.
19.
if q =< 4 then
20.
21.
console.write("hi,")
22.
23.
else
24.
25.
console.write("hello,")
26.
27.
endif
28.
29.
End Sub
30.
31.
Sub Main()
32.
33.
console.writeline(q)
Fawad Khan 0321-6386013
Page 71
Answer :
Locals: y (on line 4), q (on line 9)
Globals: q (on line 2)
Page 72
We can create the two-dimensional array shown above and assign values by doing the following:
Dim grid(4,4) As String
grid(0,3) = "A"
grid(3,2) = "B"
grid(1,4) = "C"
Console.Writeline("The content of 3,2 is:" & grid(3,2))
Page 73
Dim x, y As Integer
Dim board(3, 3) As Char
board(0, 0) = "x"
board(0, 1) = "o"
board(0, 2) = "o"
Fawad Khan 0321-6386013
Page 74
board(1, 0) = "o"
board(1, 1) = "o"
board(1, 2) = "x"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
For z = 1 To 3
Console.WriteLine("This is guess number " & z)
Next
Page 75
for white
Answer:
checkBoard(1, 1) = "b"
checkBoard(1, 2) = "w"
checkBoard(1, 3) = "b"
checkBoard(2, 1) = "w"
checkBoard(2, 2) = "b"
checkBoard(2, 3) = "w"
checkBoard(3, 1) = "b"
checkBoard(3, 2) = "w"
checkBoard(3, 3) = "b"
A much smarter way is to use a loop, this will allow for you to quickly create an board of any size you
wish. There is a question coming up that will want you to build this!
display
parameter
Answer:
sub display(checkBoard())
for x = 1 to 3
for y = 1 to 3
console.write(checkBoard(x,y))
Next
console.writeline()
Next
Page 76
w . You
might want to look for a pattern in the colour assignments for the checker board above and make
friends with the MOD function You might also go a little loopy trying to answer this question
Answer:
dim chessBoard(8,8) as char 'also chessBoard(7,7)
for x = 1 to 8
for y = 1 to 8
if (x + y) MOD 2 = 1 then
chessBoard(x,y) = "w"
else
chessBoard(x,y) = "b"
end if
next
next
display(chessBoard()) ' using a slightly updated version of the subroutine display()
If you've done this you might want to get the program to print some massive boards, whatever floats
your boat.
Page 77
Answer:
Console.Writeline(grid(3,0) & grid(3,1) & grid(3,2) & grid(3,3) & grid(3,4))
grid(2,0) = "M"
grid(2,1) = "A"
grid(2,2) = "R"
grid(2,3) = "Y"
grid(1,0) = "S"
grid(1,1) = "A" ' you could skip this
grid(1,2) = "M"
grid(1,3) = ""
grid(1,4) = ""
Page 78
Enumerated
If you are using lots of constants in your program that are all related to each other it is a good idea to keep
them together using a structure called an Enum . For example you might want to store the names of each set
of cards in a deck, instead of writing:
Const heart as integer = 1
Const club as integer = 2
Const spade as integer = 3
Const diamond as integer = 4
dim cardset as string
cardset = spade
We can bring them together in a nice neat structure called an enum:
Enum suits
HEARTS = 1
CLUBS = 2
SPADES = 3
DIAMONDS = 4
End Enum
dim cardset as suits
cardset = suits.HEARTS
This allows you to set meaningful names to the enum and its members, meaning it it easier to remember and
makes your code more readable.
We might also create separate constants to store the points of football results
Const Win as Integer = 3
Const Draw as Integer = 1
Const Lose as Integer = 0
With enums we can create a datatype called Result and store the points within it, under easy to remember
name:
Enum Result
Fawad Khan 0321-6386013
Page 79
Win = 3
Lose = 1
Draw = 0
End Enum
dim ManUvChelsea as Result
ManUvChelsea = Result.Win
Console.Writeline("ManU scored " & ManUvChelsea & " points" )
Page 80
Page 81
Page 82
Records are collections of data items (fields) stored about something. They allow you to combine several
data items (or fields) into one variable. An example at your college they will have a database storing a
record for each student. This student record would contain fields such as ID, Name and Date of Birth. The
following example that DOESN'T USE RECORDS might be simple enough for one student:
Dim studentID As Integer
Dim studentName As String
Dim studentDoB As Date
Sub Main()
Console.write("insert the id: ")
newStudentid = console.readline()
console.write("insert the name: ")
newStudentname = console.readline()
console.write("insert the Date of Birth: ")
newStudentDoB = console.readline()
console.writeline("new record created: " & newStudentid & " " & newStudentname & " " &
newStudentDoB)
End Sub
For the following input:
Page 83
But what if your college has more than one student, we'd have to write:
Dim studentID1 As Integer 'field
Dim studentName1 As String 'field
Dim studentDoB1 As Date 'field
Dim studentID2 As Integer 'field
Dim studentName2 As String 'field
Dim studentDoB2 As Date 'field
Dim studentID3 As Integer 'field
Dim studentName3 As String 'field
Dim studentDoB3 As Date 'field
...
...
Dim studentID2400 As Integer 'field
Dim studentName400 As String 'field
Dim studentDoB400 As Date 'field
It would take an awfully long time to declare them all, let alone saving writing data to them. So how do
we solve this? Well we need to combine two things we have learnt about so far, the record and the array.
We are going to make an array of student records:
Structure student 'record declaration
Dim id As Integer 'field
Dim name As String 'field
Dim DoB As Date 'field
End Structure
Sub Main()
Dim newStudents(400) As student 'declare an array of student records, a school with 401 students
for x = 0 to 400 'insert the details for each student
Console.WriteLine("insert the id")
newStudents(x).id = Console.ReadLine()
Console.WriteLine("insert the name")
Fawad Khan 0321-6386013
Page 84
newStudents(x).name = Console.ReadLine()
Console.WriteLine("insert the Date of Birth")
newStudents(x).DoB = Console.ReadLine()
next
for x = 0 to 400 'print out each student
Console.WriteLine("new record created: " & newStudents(x).id & " " & newStudents(x).name & " "
& newStudents(x).DoB)
next
End Sub
This seems to solve our problem, you might want to try it out yourself but decrease the number of
students slightly!
Page 85
Exercise: Records
Declare an record called player to store the following Role Playing Game attributes: health, name, class
(barbarian, wizard, elf), gold, gender
Answer :
Enum type
WIZARD
BARBARIAN
ELF
End Enum
Structure player 'remember Visual Basic uses structure instead of record
name as string
health as integer
gold as integer
gender as char
' class as string ' you might have already noticed, the word class is 'reserved'
' this means it is has a special purpose in VBNET and we'll have to use another
characterclass as type 'a string would work, but it's better to use an enum
End player
Creates 2 characters, Gandolf and Conan using the player record
Answer :
'you can of course give them different attributes
Dim Gandolf As player
Gandolf.name = "Gandolf"
Gandolf.health = 70
Gandolf.gold = 50
Gandolf.gender = "m"
Gandolf.class = type.WIZARD
Dim Conan As player
Conan.name = "Conan"
Conan.health = 100
Conan.gold = 30
Conan.gender = "m"
Conan.class = type.BARBARIAN
Page 86
StreamReader ,
a collection of
functions used to read data from files into our program. To get this program to work
you are going to need a file called
myfile.txt
C:\
Page 87
Writing files
As well as reading files it's important that we can write to files, this time using the StreamWriter :
'you might need this so that you can use StreamReader
Imports System.IO
Module Module1
Sub Main()
Dim filewriter As StreamWriter
Dim filename As String
Dim texttofile As String
filename = "C:/test1.txt" 'this is the location, file name and extension
of what you are writing to.
filewriter = New StreamWriter(filename)
texttofile = Console.ReadLine
filewriter.WriteLine(texttofile) 'write the line to the file
filewriter.Close()
End Sub
End Module
Page 88
filewriter As StreamWriter
filename As String
texttofile As String
line As String
Answer :
It only changes how a program or an Operating System handles the file, it doesn't
change anything inside the file
Page 89
Compilation Errors
Run-time Errors
Logic Errors
Page 90
To fix it, you have to fix the logic of the code and change line 6 to:
6. Console.Writeline("Total = " & Price + (Price * Tax))
Exercise: Validation
Name and give examples of the three error types in programming code:
Answer:
Compilation (Syntax)
Logic (Symantic)
Runtime
Page 91
What error is in the following code, how would you fix it:
1. dim x as integer
2.
3. do until x > 5
4.
5.
x = 1
6.
7.
x = x + 1
8.
9. loop
Answer :
There is a Runtime error.
the value of
1,
thus,
the loop will always end in 2 and the loop will never end. This could be fixed by moving the x = 1
instruction outside the loop, between line 1 and 2.
What error is in the following code, how would you fix it:
1. dim n as sting
2. console.writeline("enter your name")
3. n = console.readline
Answer :
The first line has a compilation (syntax) error. dim n as sting should read dim n as string
Page 92
Answer :
The third line has a Logic (semantic) error. For x = 1 to 3 should read For x = 0 to 3
What error is in the following code, how would you fix it:
1. Dim names() As Sting = {"Harry", "Dave", "Princess",
"Nicky"}
2.
3. Dim y As Integer
4.
5. y = Console.Readline()
6.
7. 'print some of the names
8.
9. For x = 0 to y
10.
11.
Console.Writeline("name " & x & " = " &
names(x))
12.
13.
Next
Answer :
Line 1 has a compilation error,
Sting
should read
String .
Runtime error on line 5, if the user inputs a value of y that is greater than 3 then the
code will break. Errors like these can be solved in a number of ways, we are going
to look at one now.
Fawad Khan 0321-6386013
Page 93
Catching errors[edit]
Dim age as integer
console.writeline("How old are you?")
age = console.readline()
console.writeline("What is your name?")
For the above code we can easily break it if we type the following:
age
to save the string cabbages into an integer. It's like trying to fit a cannon into a camel, they just
aren't compatible, and VB will definitely complain ruining all your code. What is needed is a way
in which we can stop or catch these errors, we are going to take a look at try and catch.
Dim age as integer
console.writeline("How old are you?")
Try
age = console.readline()
Catch ex As Exception
console.writeline(ex.message)
End Try
console.writeline("What is your name?")
Page 94
Exercise: Validation
Use a try and catch to avoid the issue of a person inputting a value for y that would break the array.
1. Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
2.
3. Dim y As Integer
4.
5. y = Console.Readline()
6.
7. 'print some of the names
8.
9. For x = 0 to y
10.
11.
Console.Writeline("name " & x & " = " & names(x))
12.
13. Next
Answer :
1. Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}
2.
3. Dim y As Integer
4.
5. y = Console.Readline()
6.
7. 'print some of the names
8.
9. Try
10.
11.
For x = 0 to y
12.
13.
Console.Writeline("name " & x & " = " & names(x))
14.
15.
Next
16.
17. Catch ex As Exception
18.
19.
console.writeline("Looks like we're exceeded our array index")
20.
21.
console.writeline(ex.message)
22.
23. End Try
Page 95
Corrective maintenance is necessary when a fault or bug is found in the operation of the new
system. These are software bugs which were not picked up at the formal testing stage. A
technician or the original programmers will be needed to correct the error.
Most systems have imperfections. The initial testing of the system should find many of them but
more obscure errors may only be encountered as users interact with the system day after day.
Part of the system should include a way for customers / users to report these problems. Also error
logs should be included in the system so maintenance staff can spot problems even if they are not
reported.
Page 96
Page 97
Page 98
Page 99
Page 100
Page 101
Page 102
Page 103
Page 104
Page 105
ITERATIONS
RECURSION
Recursive function is a function that is partially
defined by itself
repetitions of a process
recognized
condition fails
than recursion
Page 106
Example of recursion
function factorial(ByVal n as integer)
if n > 1 then
return n * factorial(n-1) 'recursive
call
else
return 1
end if
end function
sub main()
console.writeline(factorial(10))
end sub
Page 107
Let's build a trace table and see what happens. This trace table will be different from the ones that
you have built before as we are going to have to use a stack. If you haven't read up on stacks you
must do so before continuing:
Page 108
n Return Line
43
33
2
We now have a similar situation to before, let's store the return address and go to factorial(1)
Function call
1
2
3
4
n
4
3
2
1
Now we have another problem, we have found an end to the factorial(1). What line do we go to next? As
we are treating our trace table as a stack we'll just pop the previous value off the top and look at the last
function call we stored away, that is function call 3, factorial(2), and we even know what line to return to,
line 3:
return 2 * factorial(1)
We know that factorial(1) = 1 from the previous returned value. Therefore factorial(2) returns 2 * 1 = 2
Function call
1
2
3
4
n
4
3
2
1
Page 109
Again we'll pop the last function call from the stack leaving us with function call 2, factorial(3) and line 3.
return 3 * factorial(2)
We know that factorial(2) = 2 from the previous returned value. Therefore factorial(3) returns 3 * 2 = 6
Function call
1
2
3
4
n
4
3
2
1
Again we'll pop the last function call from the stack leaving us with function call 1, factorial(4) and line 3.
return 4 * factorial(3)
We know that factorial(3) = 6 from the previous returned value. Therefore factorial(4) returns 4 * 6 = 24
Function call
1
2
3
4
n
4
3
2
1
Return Line
3
3
3
Return Value
24
6
2
1
We reach the end of function call 1. But where do we go now? There is nothing left on the stack and we
have finished the code. Therefore the result is 24.
Page 110
Page 111
Page 112
Classes[edit]
Structures are very similar to Classes in that they collect data together.
However, classes extend this idea and are made from two different things:
Attributes - things that the object stores data in, generally variables.
Methods - Functions and Procedures attached to an Object and allowing
the object to perform actions
Page 113
two attributes:
four methods
o
o
car
and it has:
maxSpeed, fuel
refuel, drive
Unlike structures, OOP allows you to attach functions and procedures to your
code. This means that not only can you store details about you car (the
Fawad Khan 0321-6386013
Page 114
drive()
and
refuel ,
Page 115
OO - PIIE
When talking about OOP you must remember the following:
Where:
Instantiation
As we have seen a class is a template for something, you can't actually execute a class, you must instantiate it,
that is create an instance of an class in the form of an object.
dim polo as new car
'instantiation 1
escort
car
dim
as new
'instantiation 2
The code above creates an object called polo and escort, both of class type car (which we declared earlier).
We can now use all the public attributes and methods:
polo.refuel(100) 'assuming fuel starts at 0
polo.drive()
escort.refuel(50) 'assuming fuel starts at 0
escort.drive()
for x = 1 to 20
escort.drive()
polo.drive()
next
polo.refuel(10)
console.writeline("polo: " & polo.getFuel())
console.writeline("escort: " & escort.getFuel())
Page 116
Page 117
Encapsulation
You can only access private attributes and methods through an interface (public methods)
You noticed that we didn't have to use the dim statement for the attributes and we used the
word private instead. What this means is that these attributes are not directly accessible once you have
instantiated the class. Let's take our polo class as an example:
polo.fuel = 100 'this would be acceptable (but not in the exam!)
In the example we access the fuel attribute of the polo class and give the car 100 units of fuel because fuel is
declared aspublic, there are no restrictions in accessing it. However, when we try the following we run into
trouble:
polo.maxSpeed = 100 'this would be unacceptable
The reason that this wouldn't work is because we have declared the maxSpeed attribute as private. If
something is declared as private you can't access it externally, but how do you access it? The only way to
access a private method or attribute is to use an interface, or public method. In the car code example we have:
public sub setSpeed(byVal s as integer) 'declaring an interface
maxSpeed = s
end sub
Because this method is public we can call it through: polo.setSpeed(100) . And because setSpeed is
declared inside the car object, it can have access to all the private attributes and methods.
We also need to find out the speed of a car to display to the user, we can do this by creating a get routine:
Page 118
Exercise: Encapsulation
Declare a colour attribute for the car that can only be accessed through an interface
Answer :
private colour as string 'this must be private!
Answer :
public function getColour() 'it must be a function to return
a value
return colour
end function
Page 119
Answer :
1. Class actor
2.
3. Private health As Integer
4.
5. Private name As String
6.
7. Private x As Integer
8.
9. Private y As Integer
10.
11.
12.
13. Public Sub setName(ByVal p)
14.
15. name = p
16.
17. End Sub
18.
19.
20.
21. Public Sub walkforward()
22.
23. x = x + 1
24.
25. End Sub
26.
27.
28.
29. Public Sub eat()
30.
31. health = health + 10
32.
33. Console.WriteLine("Nom Nom Nom")
34.
Fawad Khan 0321-6386013
Page 120
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
End Sub
Page 121
76.
77.
78.
79.End Class
80.
Answer :
dim wizard as new actor
name
dim orc as new actor
Page 122
inheritance diagram of vehicles, all sharing attributes and functions from the parent class 'Vehicle'. Note the direction of arrows
Building on the car example above, what would happen if we wanted to declare an electric car? Well we'd
probably want to store some information on the number of batteries that it has:
class electricCar
private maxSpeed as integer
private fuel as integer 'fixed!
private numBatteries as integer 'added
public sub setnumBatteries(byVal n as integer)
numBatteries = n
end sub
public function getnumBatteries()
return numBatteries
end sub
public sub setSpeed(byVal s as integer)
maxSpeed = s
end sub
public function getSpeed() as integer
return maxSpeed
end function
public sub refuel(byVal x as integer) as integer
'.....
'HOLD ON!
end class
Page 123
Exercise: Inheritance
Declare a new class called limo that has attributes numSeats and colourSeats; and the ability to interface
with them
Answer :
class limo
inherits car 'declares what attributes and methods you
are inheriting
private numSeats as integer 'must be private
private colourSeats as integer 'must be private
public sub setnumSeats(byVal s as integer) 'interface set
numSeats = s
end sub
Fawad Khan 0321-6386013
Page 124
Inheritence diagrams
Page 125
The Truck inherits the Vehicle and adds its own attributes and methods
The Car inherits the Vehicle and adds its own attributes and methods
The Electric inherits the Car (and therefore the Vehicle) and adds its own attributes and methods
The Petrol inherits the Car (and therefore the Vehicle) and adds its own attributes and methods
Note the direction of arrows, you'll get marked down for putting them in the wrong direction.
Answer :
vehicle
Page 126
Page 127
Page 128
Page 129
In this example we keep adding (pushing) books to the stack. If we want to get at the bottom book about
Cars, we must first remove (pop) all the books above it. Hence First In Last Out (FILO)
Page 130
Holding return addresses and system states for recursive function calls
Exercise: Stacks
Draw the stack after each of the following commands, starting with an empty
stack. What does the stack achieve:
1. Push 'Annabelle'
2. Push 'Chris'
3. Push 'Hemingway'
4. Push 'James'
5. Pop
6. Pop
7. Pop
8. Pop
Page 131
Answer :
1. Pop
2. Pop
3. Push 'Sand'
4. Push 'Witches'
If we have an empty Stack what do we set the pointer TopOfStack to?
Answer :
0 or null
Page 132
&
console.readline()
Page 133
Keyboard Buffer - you want the letters to appear on the screen in the order you press them. You might
notice that when your computer is busy the keys you press don't appear on the screen until a little while
after you press them. When they do appear they appear in the order you press them
Printer Queue - you want print jobs to complete in the order you sent them, i.e. page 1, page 2, page 3,
page 4 etc. When you are sharing a printer several people may send a print job to the printer and the
printer can't print things instantly, so you have to wait a little while, but the items output will be in the order
you sent them
There are several different types of queues such as the ones described below:
Linear
In this queue form, elements are able to join the queue at one end and can exit from the queue at the other
end. First In First Out (FIFO).
Page 134
Page 135
Answer :
Root = 5
Left subtree = 2, 1, 4, 3
Leafs = 1, 3, 7, 9
Page 136
Page 137
For the tree above a tree traversal can be performed in 3 different ways.
Preorder
The first type of traversal is pre-order whose code looks like the following:
sub P(TreeNode)
Output(TreeNode.value)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
end sub
This can be summed up as
1. Visit the root node (generally output this)
2. Traverse to left subtree
3. Traverse to right subtree
And outputs the following: F, B, A, D, C, E, G, I, H
In-order
The second(middle) type of traversal is in-order whose code looks like the following:
sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
Page 138
Post-order
The last type of traversal is post-order whose code looks like the following:
sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
Output(TreeNode.value)
end sub
This can be summed up as
1. Traverse to left subtree
2. Traverse to right subtree
3. Visit root node (generally output this)
And outputs the following: A, C, E, D, B, H, I, G, F
Page 139
Rule of thumb
There is an easier way to remember how to do this and if you are struggling for time in the exam you can try
this way:
1. Check that the code is left traversal followed by right traversal
2. Check the position of the output line
3. draw the dots on the nodes
4. draw a line around the tree
5. follow the line and write down each node where you meet a dot
So let's take a look at what that all means. First of all take a look at the code. If the code has the left tree
traversal before the right tree traversal we can proceed (this is true in all cases above and below). How we
need to find out where the output line is.
sub P(TreeNode)
'Output(TreeNode.value) REM Pre-Order
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
'Output(TreeNode.value) REM In-Order
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
'Output(TreeNode.value) REM Post-Order
end sub
Depending on where the line to output the node value is this will tell you what sort of tree order traversal they
are asking you to do. NOTE: If you have In order traversal don't jump too soon, the tree may not be sorted!
But how does this help? The next thing you need to do is put a little mark on each node of the tree as follows:
Page 140
NOTE: They may try to trick you using one the following ways:
The binary tree is not sorted and they want you to perform in-order traversal
If you have time work it out properly and use this method to help.
Answer :
Page 141
For the following binary tree what does the following code do?
sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
Output(TreeNode.value)
end sub
Answer :
post-Order traversal because the output is at the bottom and the left node is traversed before the right node.
Page 142
Answer :
Page 143
Bubble sort
Bubble sort is also known as exchange sort. It repeatedly visits the array and compares two item at a time. It swaps
these two items if they are in the wrong order. It continues to check the array until no swaps are needed that
means the array is sorted.
Programming code
Page 144
30
15
25
In the above example, nested loops are used to sort the array. The outer loop moves from 0 to 4 and with each
iteration of outer loop, inner loop moves from 0 to e - (i+1).
First of all, the value of I is 0 so the focus of outer loop is on the first element of the array. The sorting process will
work as follows:
Pass 1
Iteration 1
10
30
15
25
j =0 so the statement arr(j) > arr(j+1) compares 10 with 30. As 10 is not greater than 30, there will be no change in
the array.
Iteration 2
10
30
15
25
j=1 so the statement arr(j) > arr(j+1) compares 30 with 15. As 30 is greater than 15, both values will be
interchanged and the array will be as follows:
10
15
30
25
10
15
30
25
Iteration 3
j=2 so the statement arr(j) > arr(j+1) compares 30 with 25. As 30 is greater than 15, both values will be
interchanged and the array will be as follows:
10
15
25
30
Page 145
Iteration 4
10
15
25
30
j=3 so the statement arr(j) > arr(j+1) compares 30 with 5. As 30 is greater than 5, both values will be interchanged
and the array will be as follows:
10
15
25
30
At this point, the inner loop is completed and the largest value in array has moved in the last element. It means that
the position of largest value is now finalized. Now the control moves to the beginning of outer loop and the value of
i becomes 1.
Pass 2
Iteration 1
10
15
25
30
j=0 so the statement arr(j)>arr(j+1) compares 10 with 15. As 10 is not greater than 15, there will be no change in
the array.
Iteration 2
10
15
25
30
j=1 so the statement arr(j) > arr(j+1) compares 15 with 25. As 15 is not greater than 25, there will be no change in
the array.
Iteration 3
10
15
25
30
j=2 so the statement will arr(j) > arr(j+1) compares 25 with 5. As 25 is greater than 5, both values will be
interchanged and the array will be as follows:
10
15
25
30
Page 146
Pass 3
Iteration 1
10
15
25
30
j=0 so the statement arr(j) > arr(j+1) compares 10 with 15. As 10 is not greater than 15, there will be no change in
the array.
Iteration 2
10
15
25
30
j=1 so the statement arr(j) >arr(j+1) compares 15 with 5. As 15 is greater than 5, both values will be interchanged.
The array will be as follows:
10
15
25
30
At this point, the inner loop is completed and the third largest value in the array has moved in the third last
element. It means that the position of third largest value is now finalized. Now the control moves to the beginning
of outer loop and the value of i becomes 3.
Pass 4
Iteration1
10
15
25
30
j=0 so the statement arr(j)>arr(j+1) compares 10 with 5. As 10 is greater than 5, both values will be interchanged
and the array will be as follows:
Page 147
10
15
25
30
At this point, the inner loop is completed and the fourth largest value in the array has moved in the fourth last
element. It means that the position of fourth smallest value is now finalized. The position os smallest number is also
automatically finalized. Now the outer loop also terminates and the array is sorted in ascending order.
Page 148
Binary Sort
Page 149