Sunteți pe pagina 1din 149

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: A program


When you first load Visual Studio and select to run a Console Application, you will be presented with
some source code:
module module1
sub main()
end sub
end module

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

Fawad Khan 0321-6386013

Page 1

Fundamental of programming for Computer Science 9608 Paper 2

We'll take a look at each line:


1. module module1 - this line tells the computer that this particular program is called module1
2. sub main defines the section of code that is executed first
3. console.writeline("Hello...29") - this line writes plain text to the console window. There are
lots of other console commands we can perform such as console.beep and console.color. We'll
learn about them in the input/output section
4. console.writeline("6 * 6 = " & 6 * 6) - this writes out a combination of text (everything
between the "speech marks") and calculation (6*6), joining the two together with the ampersand
(&).
5. console.readline() - If you are running VB from a command line this won't be necessary, but
for people using Visual Studio it is. console.readline() waits for you to hit the return key.
Modern computers are very fast and if you didn't have this then the words displayed on the screen
would appear and then disappear too fast for the eye to see, the screen would appear, then instantly
disappear, take this line out and see what I mean.
6. end sub defines the end of the main code section.
7. end module - signifies the end of the small program we have written
This should output the following:

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:

Fawad Khan 0321-6386013

Page 2

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Hello World!


Create a short program to write the following to the screen, replacing the name Dave with your own name
(unless it also happens to be Dave):

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

Fawad Khan 0321-6386013

Page 3

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Variables


Let's take a look at this program:
1.
2.
3.
4.
5.
6.
7.
8.

Dim name As String


Dim age As Integer
name = "Peter"
age = 29
Console.WriteLine("Hello " & name & " you are " & age & " years old")
Console.WriteLine("This also means you are " & age * 12 & " months old")
Console.WriteLine("Bye " & name & "!")
Console.ReadLine()

You might be expecting it to print out:


Hello name you are age years old

But instead it says:

Fawad Khan 0321-6386013

Page 4

Fundamental of programming for Computer Science 9608 Paper 2

What a friendly program! Let's break it down line by line:


1. dim is a variable declaration, creating a temporary data store, a variable, and calling it
name It also makes sure that whatever goes into name will be a string by setting it to as
string
2. We declare another variable called age and make sure it is stored as an integer (a whole
number)
3. The variable name that we created earlier is now assigned a value and as it's a string we
better use speech marks - "Peter"
4. The variable age that we created earlier is now assigned a value and as it's an integer we
better not use speech marks - 29
5. This line writes things to the screen, starting with the text "Hello " which attaches that
variable we saw earlier to, but instead of putting the variable name, it puts the contents of
the variable ("Hello Peter"), then it attaches some more text ("Hello Peter you are ") and
adds another variable, age. Even though age is an integer we can stick it together with a
string ("Hello Peter you are 29"). Then finally it uses the ampersand once more to attach the
final piece of text ("Hello Peter you are 29 years old)
6. This line works in pretty much the same way, but it does a calculation, working out the age
in months. Computers are like giant calculators and you can perform all the sums you can
perform on your little pocket calc performed and far far more using them!
7. The great things about variables is that we can use them again and again, here we say "Bye
" and using an ampersand stick on the name of the person. This is great, by using a variable
we only need to write "Peter" once and save it as name. If someone else came along and
wanted to change the program they just need to change the value of name. Programming is
all about being as lazy as possible.
8. Good old console.readline() stops the screen disappearing too fast

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

Fundamental of programming for Computer Science 9608 Paper 2

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.

dim identifierName as integer


identifierName = 7
console.writeline("The value stored in identifierName is: " & identifierName)

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.

dim name as string


dim age as integer
name = "Syeda"
age = 31
console.writeline("Hello " & name & " you are " & age & " years old")
console.writeline("This also means you are " & age * 12 & " months old")
console.writeline("This also means you are " & age * 365 & " days old")
console.writeline("This also means you are " & age * 365 * 24 & " hours old")
console.writeline("This also means you are " & age * 365 * 24 * 60 & " minutes old")
console.writeline("This also means you are " & age * 365 * 24 * 60 * 60 & " seconds old")
console.writeline("Bye " & name & "!")
console.readline()

Fawad Khan 0321-6386013

Page 6

Fundamental of programming for Computer Science 9608 Paper 2


Give a good reason why you made age a variable in the previous code

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()

Fawad Khan 0321-6386013

Page 7

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Comments


Over the course of the next few chapters you might see a lot of text in the code examples that doesn't seem
to do anything other than aid understanding of the code. This text is called a comment and if you have this
book in colour you'll see that these comments are highlighted in green.
Comment - programmer-readable annotation in the source code of a computer program that helps
programmers understand the code but is usually ignored at run time
In Visual Basic all comments start with an apostrophe (') or the word REM. Let's take a look at a quick
example:

' this is a comment


dim a, b, c as string' declare variables to store names
'''' read the three names ''''
a = console.readline()
b = console.readline()
c = console.readline()
console.writeline("the names are :" & a & b & c)

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)

Fawad Khan 0321-6386013

Page 8

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Input and output


An important part of computer code is allowing your user to input data into the program,
things such as text, key presses or even a data feed from a motion sensor games controller.
Once the data is in the program you want the system to output responses, these may take
the form of output to a screen: graphics, text, output to a sound device, printed documents or
data output to another program.
For this unit you need to be familiar with a few input and output commands. The little black
box that appears on your screen is called the console. In VB.NET all the commands to read
and write from this are accessed from the console. command, let's take a look at some:
Outputs
For the AS course it is unlikely you will need anything beyond the print to screen command
and the write to file command (see later). There are two write to screen commands that you
should be familiar with:
console.write("Hello") 'writes the word hello to the screen
console.writeline("Hello") 'writes the word Hello to the screen and adds a carriage return (new line)

Let's see an example of this in action:


console.write("Hello ")
console.write("how ")
console.write("are ")
console.writeline("you?")
console.writeline("I'm fine thank ")
console.write("you.")

This would output the following:

Fawad Khan 0321-6386013

Page 9

Fundamental of programming for Computer Science 9608 Paper 2

Notice the difference between a writeline and a write command.

Extension: Console methods


We can do a lot of things with the console command. If you are using Visual Studio then type the
following:
Console.

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

Fawad Khan 0321-6386013

Page 10

Fundamental of programming for Computer Science 9608 Paper 2

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 )

Fawad Khan 0321-6386013

Page 11

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Inputs and Outputs


What does the following code output:
console.writeline("The ")
console.write("Cat")
console.write("sat ")
console.writeline("on ")
console.writeline("the " & "mat")

dim num as integer = 19


console.writeline("The average age ")
console.write("of a combat soldier ")
console.write("in Vietnam was " & num)

Answer:
console.writeline("My favourite colours:")
console.writeline("Red")
console.writeline("Blue")

Fawad Khan 0321-6386013

Page 12

Fundamental of programming for Computer Science 9608 Paper 2

What would the following look like:


dim age as string
dim name as integer
console.writeline("Enter your name: ")
age = console.readline()
console.writeline("Enter your age: ")
name = console.readline()
console.writeline("Hello " & name & ". You are " & age & " years old ")
for the input:
Nobby
16

Whoops! Fix this:


Answer:
dim age as integer
dim name as string
console.writeline("Enter your name: ")
name = console.readline()
console.writeline("Enter your age: ")
age = console.readline()
console.writeline("Hello " & name & ". You are " & age & " years old ")

Fawad Khan 0321-6386013

Page 13

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Arithmetic operators


Operator - a programming device that performs a function on one or more inputs, for example
arithmetic operators (+,-,/,*)
Visual Basic .NET provides a basic set of operators to calculate simple arithmetic.
+
*
/
\
Mod
^
&

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).

Fawad Khan 0321-6386013

Page 14

Fundamental of programming for Computer Science 9608 Paper 2

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.

Fawad Khan 0321-6386013

Page 15

Fundamental of programming for Computer Science 9608 Paper 2

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.

Fawad Khan 0321-6386013

Page 16

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Built-in data types


All programming languages have built in data types that are used when declaring variables (though
not all programming languages have variables - don't worry about this yet though!). Some very
common data types, and the ones you need to know for the exam, are as follows:

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")

But wait a second, this gives you an odd output, it says:

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

Fundamental of programming for Computer Science 9608 Paper 2

Integers, Bytes, Real, Singles, Doubles = Plain assignment without speech marks
exampleNumber = 7.65

Boolean = Plain assignment without speech marks


paidMember = TRUE

String, Char = Assignment with speech marks


name = "Henry"

Date = Assignment with speech marks


doB= "12/12/45"

Exercise: Data types


Using the correct datatype declare variables for a person's:

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

Fawad Khan 0321-6386013

Page 18

Fundamental of programming for Computer Science 9608 Paper 2


dim wheelNum as integer
dim topSpeed as single
dim hasElectricWindows as char

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

Give two reasons why is it important to get the correct datatypes:

Answer:

Prevents mistakes in code and calculations at run time


Makes for smaller and faster programs

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:

Fawad Khan 0321-6386013

Page 19

Fundamental of programming for Computer Science 9608 Paper 2

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()

Fawad Khan 0321-6386013

Page 20

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Constant Definitions


Constants are like variables in their declarations and the ability to look at the value stored inside them,
however you can not change the values while the program is running, the value of a constant remains
(rather unsurprisingly) constant.

Example: Declaring pi as a constant


Const pi as Single = 3.14
console.writeline(pi)

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.

const pi as single = 3.14


dim r as single
console.write("Insert radius: ")
r = console.readline()
console.writeline("area = " & pi * r * r)
console.writeline("circumference= " & 2 * pi * r)
console.readline()

Fawad Khan 0321-6386013

Page 21

Fundamental of programming for Computer Science 9608 Paper 2


Write a program that works out the cost of two clothing items showing the price, VAT, and price inclusive
of VAT. VAT = 17.5%. For example

Answer:
1.
2.
3.
4.
5.
6.
7.
8.
9.

const VAT as single = 0.175


dim price1, price2 as single
console.write("Insert price of item 1: ")
price1 = console.readline()
console.write("Insert price of item 2: ")
price2 = console.readline()
console.writeline("item 1 = " & price1 & " + " & price1 * VAT & " VAT = " & price1 * (VAT + 1))
console.writeline("item 2 = " & price2 & " + " & price2 * VAT & " VAT = " & price2 * (VAT + 1))
console.readline()

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.

Fawad Khan 0321-6386013

Page 22

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Selection


An important part of programming is the use of selection, that is the ability to do something if certain
criteria is met. This may be as simple as increasing your health bar in a computer game if you eat a
chicken drumstick or inserting the cooling rods into the nuclear reactor if the temperature exceeds a
certain value.
IF Statement

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

Fawad Khan 0321-6386013

Page 23

Fundamental of programming for Computer Science 9608 Paper 2

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>

Fawad Khan 0321-6386013

Page 24

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 25

Fundamental of programming for Computer Science 9608 Paper 2


In all other situations the program should say: "Sorry I don't know how to help". Using one IF statement write
code to handle the above:
dim feel as string
dim exercise as string
console.writeline("How do you feel today: Happy or Sad?")
feel = console.readline()
console.writeline("Have you had some exercise: Yes or No?")
exercise = console.readline()
If feel = "Sad" AND exercise = "No" Then
console.writeline("Go for a walk, you might feel better")
Else
console.writeline("Sorry I don't know how to help")
End If

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")

Fawad Khan 0321-6386013

Page 26

Fundamental of programming for Computer Science 9608 Paper 2


End If

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

Fawad Khan 0321-6386013

Page 27

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Nested IF statements


Write nests of IF statements for the following:
A car can be hired when a person is over 21 and not intoxicated.

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

Fawad Khan 0321-6386013

Page 28

Fundamental of programming for Computer Science 9608 Paper 2


Create a login screen to do the following:

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

Fawad Khan 0321-6386013

Page 29

Fundamental of programming for Computer Science 9608 Paper 2

Extension: Single line IF statements


As you should be aware by now a lot of programming is doing things as quickly as possible. You might be
fed up with writing long if statements, having to keep hitting that enter key to make new lines. There is a
faster way to code: single line IF statements.
If(input >= 18,console.writeline("drink beer"),console.writeline("drink cola"))

This is a much shorter way of writing:


If input >= 18 then
console.writeline("drink beer")
Else
console.writeline("drink cola")
End if

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.

Fawad Khan 0321-6386013

Page 30

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 31

Fundamental of programming for Computer Science 9608 Paper 2

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

Exercise: Case statements


Create a program where someone types in the name of an animal and it outputs the sound the animal
makes. The animals it should handle are:

Pig - Oink
Cow - Moo
Bear - Grr
Sheep - Baa
Tiger - Grr
everything else - Meow

Try and complete this task by only using 5 case statements.


Answer:
Dim animal As string
animal = console.readline()
Select Case animal
Case "Pig"
Console.WriteLine("Oink")
Case "Cow"
Console.WriteLine("Moo")
Case "Bear", "Tiger"
Console.WriteLine("Grr")
Case "Sheep"
Console.WriteLine("Baa")
Case Else

Fawad Khan 0321-6386013

Page 32

Fundamental of programming for Computer Science 9608 Paper 2


Console.WriteLine("Meow")
End Select

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

Remember to make sound you use:


console.beep(2000,500) 'beep at 2000Hz for 0.5 seconds

Fawad Khan 0321-6386013

Page 33

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 34

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Iteration


An incredibly important part of computing is the idea of iteration, that is repeating the same thing again
and again. You probably use iteration every day. Take writing lines in a detention for example; you write
some lines, check to see if you have met the line limit, and if you haven't you write some more lines,
check if you have met the line limit and so on, until you do meet the line limit and then you can stop.
'Programmers are lazy and can get computers to write detention lines for them
'they are also lazy as they can do a declaration and assignment at the same time:
dim count as integer = 0
While count <= 100
console.writeline(count & ". I should always do my programming homework.")
count = count + 1
End While

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!")

Fawad Khan 0321-6386013

Page 35

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: While Loops

Write a program that counts from 20 to 60 inclusive like so:

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

Fawad Khan 0321-6386013

Page 36

Fundamental of programming for Computer Science 9608 Paper 2


console.writeline(count & " * " & times & " = " & count * times)
count = count + 1
End While

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

The while loop: For example:


While not top speed Do
increase speed
End
dim speed as integer = 0
While speed < 120
console.writeline(speed)
speed = speed + 1
End While

Fawad Khan 0321-6386013

Page 37

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 38

Fundamental of programming for Computer Science 9608 Paper 2

Visual Basic handles this with some slight syntax differences


console.write("how old are you?")
age = console.readline()
Do
console.writeline(age & " year olds should attend school!")
age = age + 1
Loop Until age > 17
console.writeline(age & " is too old to attend school!")
This is great for young students:

Fawad Khan 0321-6386013

Page 39

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Do While and While Do


For the dodgy example above re-write the Do While as a While Do loop

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!")

Be careful when you use each loop!

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

Fawad Khan 0321-6386013

Page 40

Fundamental of programming for Computer Science 9608 Paper 2

It is far easier to use in vb


For speed = 0 to 120
drive()
Loop
For loops also allow you to count downwards. For example if you creating a timer that counts down to a
target. To do this we use the step - 1 code, making the following code:
For x = 10 To 1 Step -1
Console.Write(x & ",")
Next
console.writeline("Test over!")
Display:

Exercise: For loops


Write a for loop to display the words "I will eat my greens" 40 times:
Answer :
for x = 1 to 40
console.writeline("I will eat my greens")
next

Fawad Khan 0321-6386013

Page 41

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 42

Fundamental of programming for Computer Science 9608 Paper 2

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!")

Fawad Khan 0321-6386013

Page 43

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Built-in functions


Arithmetic functions

You'll have to be familiar with several


Round

The round function is used to round numbers to a limited number of decimal places using the Math.Round()
function

Math.Round(1.94, 1) 'Returns 1.9


Math.Round(1.95, 1) 'Returns 1.9 !0.5 rounds down!
Math.Round(1.96, 1) 'Returns 2.0
Math.Round(1.9445, 2) 'Returns 1.94
Math.Round(1.9545, 3) 'Returns 1.954
Math.Round(6.765, 2) 'Returns 6.76
Math.Round(1.9445) 'Returns 2 - the equivalent of saying round to 0 dp

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.

Extension: Random numbers


An essential part of most games is the ability to use random numbers. These might be used to randomly
place gold coins on a map, or to calculate whether you hit a target with a rifle at some distance.
Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()

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

Fawad Khan 0321-6386013

Page 44

Fundamental of programming for Computer Science 9608 Paper 2


Dim guess as Integer
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
console.writeline("Too High")
end if
if guess < randomNumber
console.writeline("Too Low")
end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")

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

Fawad Khan 0321-6386013

Page 45

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Arithmetic function


What does the following code output:
dim num1 as single = 12.75
dim num2 as single = 12.499
dim total as single
num2 = Math.Round(num2, 1)
num1 = Math.Truncate(num1)
total = num1 + num2
console.writeline(Math.Round(total))

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))

Fawad Khan 0321-6386013

Page 46

Fundamental of programming for Computer Science 9608 Paper 2

String handling functions


Very popular examination questions involve manipulating strings. These simple functions will help you
with this task.
Length
This function is used to find the length of any string you pass it, counting all the characters, including the
spaces. In visual basic to find the length of a string we use the Len("some string") function that returns the
integer length of the string that it has been passed:
someText = "Gary had a little lamb"
Console.writeline(Len(someText))

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"))

Fawad Khan 0321-6386013

Page 47

Fundamental of programming for Computer Science 9608 Paper 2

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?")

Fawad Khan 0321-6386013

Page 48

Fundamental of programming for Computer Science 9608 Paper 2

String conversion functions


When you declare a variable you give it a datatype. This datatype restricts the values that you can place
into the variable. For example:
dim age as integer
would allow: age = 34
would NOT allow: age = "cabbages"
This seems to make sense, but what would happen when you try to place a real number into a integer:
dim age as integer
age = 34.3
console.writeline(age)

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)

Exercise: String functions


Write a short program to tell someone how many letters they have in their name (just in case they don't
know!), for example:

Fawad Khan 0321-6386013

Page 49

Fundamental of programming for Computer Science 9608 Paper 2

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)

A telephone number has been typed into a computer as a string: (01234)567890


dim phonenum as string = "(01234)567890"
Write some code to output the number without brackets:

Fawad Khan 0321-6386013

Page 50

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 51

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 52

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: One-Dimensional Arrays

A diagram showing how a 2d array works, the equivalent of the following:


dim animals(3) as string
animals(0) = "Dog"
animals(2) = "Cat"

Dim friends(0 To 2) As String


friends(0) = "Barry"
friends(1) = "Aubrey"
friends(2) = "Gertrude"

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"}

You can pick out individual items by using their index


Console.WriteLine(friends(2))
Console.WriteLine(friends(0)

Fawad Khan 0321-6386013

Page 53

Fundamental of programming for Computer Science 9608 Paper 2

You can treat indexed array items as variables and change their values:
friends(0) = console.readline()

Exercise: One-Dimensional Arrays

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"}

Write code to output the first and last animal

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))

Fawad Khan 0321-6386013

Page 54

Fundamental of programming for Computer Science 9608 Paper 2


Next

Would print out:

To overwrite something, you treat it like a variable:


friends(1)="Peter"
For x As Integer = 0 To 2
Console.WriteLine(friends(x))
Next
Would output:

Fawad Khan 0321-6386013

Page 55

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: One-Dimensional Arrays


What is the output of the following code:

dim primes() as integer = {2,3,5,7,11,13,17,19,23}


dim count = 8
While count >= 0
console.write(primes(count) & ", ")
count = count - 1
end while

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

Fawad Khan 0321-6386013

Page 56

Fundamental of programming for Computer Science 9608 Paper 2

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

Extension: For each


Sometimes you might not know the length of an array that you area dealing with yet you will still want to
cycle through all the elements. If you don't know what numbers to put into the for x = 0 to ?? code then
how will you cycle through everything? Visual Basic and most languages offer a for each routine that
allows you to look at each element until you find the last one. This makes for far more robust code where
you don't have to keep changing the variables of loops each time you change the size of arrays:
Dim someNumbers() as integer = {1,2,3,4,5,6,7,23,77}
For Each n In someNumbers
Console.Write(n & ", ")
Next
The above code would output:

Fawad Khan 0321-6386013

Page 57

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Functions and Procedures

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

structure your programming

Easily incorporate other peoples 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

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 59

Fundamental of programming for Computer Science 9608 Paper 2

'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:

Exercise: Functions and Procedures


What is the difference between a function and procedure?
Answer:
Functions return values, Procedures don't

Why would you use subroutines (functions and procedures) in your code?
Answer:

They help you structure your code

They allow you to create a common routine once and re-use as many times as you want

They allow you to share code with other programs

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

Fundamental of programming for Computer Science 9608 Paper 2

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))

Sub nameTimes(name, num)


for x = 1 to num
console.writeline(name)
next
End Sub
For the procedure above list:

the identifier

the parameters, what are their data types?

create a procedure call to print out the name "Kane" 5 times.

Fawad Khan 0321-6386013

Page 61

Fundamental of programming for Computer Science 9608 Paper 2

Answer :

identifier = nameTimes

parameters = name (string) and num (integer)

nameTimes("Kane",5)

Fawad Khan 0321-6386013

Page 62

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 63

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 64

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: ByRef and ByVal


Sub Main()
dim a as integer = 7
dim b as integer = 8
Add(a,b)
console.writeline(a)
End Sub
Sub Add(ByXXX num1 as integer, ByXXX num2 as integer)
num1 = num1 + num2
End Sub
What is the output of the above code when ByXXX = ByVal?
Answer:

What is the output of the above code when ByXXX = ByRef ?

Sub Swap(ByRef p as string, ByVal q as string)


dim temp as string
temp = p
p=q
q = temp
console.writeline(p & " - " & q)
End Sub
Sub Main()
dim s1 as string = "hello"
dim s2 as string = "goodbye"
Swap(s2, s1)
console.writeline(s2 & " - " & s1)
End Sub
What is the output of the above code?

Fawad Khan 0321-6386013

Page 65

Fundamental of programming for Computer Science 9608 Paper 2

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.

Fawad Khan 0321-6386013

Page 66

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Global and Local Variables


Global variable - declared at the start of the program, their global scope means they can be used in any procedure
or subroutine in the program

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

What would the output be?

Fawad Khan 0321-6386013

Page 67

Fundamental of programming for Computer Science 9608 Paper 2

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

We can visualise the scope of the different variables

Fawad Khan 0321-6386013

Page 68

Fundamental of programming for Computer Science 9608 Paper 2

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 a variable is declared inside a function or a procedure it is a local variable

If a variable is declared inside a iterative or selective statement it is local

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

Fawad Khan 0321-6386013

Page 69

Fundamental of programming for Computer Science 9608 Paper 2


List the global and local variables for the following. What will be the output for input 16:
1. Module calcAge
2.
3. Sub Main()
4.
5. dim age as integer
6.
7. console.writeline("age?")
8.
9. age = console.readline()
10.
11.
printMonths(age)
12.
13.
printDays(age)
14.
15. End Sub
16.
17. Dim months as integer
18.
19. Sub printDays(a)
20.
21.
Dim d as integer
22.
23.
d = a * 365
24.
25.
console.writeline(d)
26.
27. End Sub
28.
29. Sub printMonths(a)
30.
31.
months = a * 12
32.
33.
console.writeline(months)
34.
35. End Sub
36.
37.End Module

Answer:
Locals: age, d
Globals: months

Fawad Khan 0321-6386013

Page 70

Fundamental of programming for Computer Science 9608 Paper 2

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

Fundamental of programming for Computer Science 9608 Paper 2


34.
35.
sayHello()
36.
37.
sayGoodbye()
38.
39.
console.writeline(q)
40.
41.
End Sub
42.
43. End Module

Answer :
Locals: y (on line 4), q (on line 9)
Globals: q (on line 2)

Fawad Khan 0321-6386013

Page 72

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Two-Dimensional Arrays


You have already learnt how to use one dimensional arrays in your computer programs. You should be
familiar with code such as:
Dim friends(6) As String
friends(0) = "Barry"
friends(1) = "Monica"
friends(2) = "Xiao"
This is great for storing lists of things, but what about if we want to simulate something more complex
such as a game board or a map? Wouldn't it be great if we could use a two-dimensional array?
Most major programming languages allow you to use two-dimensional arrays. They work in much the
same way as a one-dimensional array but allow you to specify a column index and a row index.

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))

Fawad Khan 0321-6386013

Page 73

Fundamental of programming for Computer Science 9608 Paper 2

Example: Two-Dimensional Arrays


Two-dimensional arrays are very useful and a good place to get started is to create your own version of
the game Battleships with a 4 cell by 4 cell grid. See if you can win, or even break it!
We are modelling the following board using the two dimensional board variable:

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

Fundamental of programming for Computer Science 9608 Paper 2

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

Console.Write("please insert you x location:")


x = Console.ReadLine()
Console.Write("please insert you y location:")
y = Console.ReadLine()
If board(x, y) = "x" Then
Console.WriteLine("you win!")
End If

Fawad Khan 0321-6386013

Page 75

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Two-Dimensional Arrays


Declare an array to make a small checkers board of type char, 3 squares by 3 squares
Answer:
dim checkBoard(3,3) as char 'also checkBoard(2,2)

create a chequered pattern using

for black and

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!

Write a sub routine to

display

this board (HINT: you need loops), that takes checkBoard as a

parameter
Answer:
sub display(checkBoard())
for x = 1 to 3
for y = 1 to 3
console.write(checkBoard(x,y))
Next
console.writeline()
Next

Fawad Khan 0321-6386013

Page 76

Fundamental of programming for Computer Science 9608 Paper 2

Declare a chessBoard (8*8 squares), programmatically colour it in with

for black and

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.

Using the following two-dimensional array, grid(4,4):

Write code to output the name CRAIG


Insert MARY on row 2 (the third row)
Overwite STEVE with SAM

Fawad Khan 0321-6386013

Page 77

Fundamental of programming for Computer Science 9608 Paper 2

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) = ""

Fawad Khan 0321-6386013

Page 78

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: User-defined data types


You have already met a variety of built-in datatypes with integers, strings, chars and more. But often these
limited datatypes aren't enough and a programmer wants to build their own datatypes. Just as an integer is
restricted to "a whole number from -2,147,483,648 through 2,147,483,647", user-defined datatypes have
limits placed on their use by the programmer.
Enumerated, subrange, sets

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

Fundamental of programming for Computer Science 9608 Paper 2

Win = 3
Lose = 1
Draw = 0
End Enum
dim ManUvChelsea as Result
ManUvChelsea = Result.Win
Console.Writeline("ManU scored " & ManUvChelsea & " points" )

Exercise: Enumerated types


Declare an enum called months that holds the months along with how many days in each for a non-leap
year
Answer :
Enum months
January = 31
February = 28
March = 31
April = 30
May = 31
June = 30
July = 31
August = 31
September = 30
October = 31
November = 30
December = 31
End Enum

Fawad Khan 0321-6386013

Page 80

Fundamental of programming for Computer Science 9608 Paper 2

What would the following code do:


Enum DayOfWeek
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
Sunday = 7
End Enum
Answer:

Fawad Khan 0321-6386013

Page 81

Fundamental of programming for Computer Science 9608 Paper 2

Records and Fields


In VB, records are known as structures
Record - a value that contains other values, indexed by names

Field - an element of a record


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:

Fawad Khan 0321-6386013

Page 82

Fundamental of programming for Computer Science 9608 Paper 2

Records and Fields

In VB, records are known as structures

Record - a value that contains other values, indexed by names

Field - an element of a record

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:

Fawad Khan 0321-6386013

Page 83

Fundamental of programming for Computer Science 9608 Paper 2

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

Fundamental of programming for Computer Science 9608 Paper 2

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!

Fawad Khan 0321-6386013

Page 85

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 86

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: File handling


Reading files[edit]

A common function needed in programs is to load data: saved games, text


documents, spreadsheets. To do this you'll need the

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

address of, for example the root of the

C:\

and put it into a location you know the full


drive:

'you might need this so that you can use StreamReader


Imports System.IO
Module Module1
Sub Main()
Dim filereader As StreamReader
Dim filename As String
Console.Write("name of file to load:")
filename = Console.ReadLine() 'this must be the
full path of the file and the file extension
filereader = New StreamReader(filename)
Console.WriteLine("contents of file:")
Console.WriteLine(filereader.ReadToEnd()) 'write
the whole file
'you can also use line = filereader.ReadLine() to
read a single line
filereader.Close()
End Sub
End Module
The above code would produce the following:

Fawad Khan 0321-6386013

Page 87

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 88

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Reading and Writing Files


write code to save a shopping list typed in by a user (they finish typing the list
by entering a blank line) to a file called specified by the user
Answer :
Imports System.IO
Dim
Dim
Dim
Dim

filewriter As StreamWriter
filename As String
texttofile As String
line As String

Console.Writeline("Please insert your shopping list:")


While line <> ""
line = Console.ReadLine()
If line <> "" Then
texttofile = texttofile + line
End If
End While
Console.Writeline("Where would you like to save it (give full location):")
filename = Console.Readline()
filewriter = New StreamWriter(filename)
filewriter.WriteLine(texttofile) 'write the line to the file
filewriter.Close()

What does the extension of a file change about a file?

Answer :
It only changes how a program or an Operating System handles the file, it doesn't
change anything inside the file

Fawad Khan 0321-6386013

Page 89

Fundamental of programming for Computer Science 9608 Paper 2

Fundamentals of Programming: Validation


Error types
When you write a program it often won't work as you expect. It might not compile, it might crash when
you run it, or it might give you the wrong result. These are all errors with your code and we can place
them into 3 different error categories:

Compilation Errors

Run-time Errors

Logic Errors

Let's take a look at what each of them mean.


Compilation (Syntax) error
You have probably met this error a lot, when you try and run your program it won't compile, giving you an
error message. If you are using something like Visual Studio it will even underline the problem code with a
blue squiggly line. There is a problem with the structure, or syntax, of the code that you have written. This
might be a situation where you have forgotten to add a closing bracket or you have misspelt a key word.
Take a look at this example:
For x = 1 two 9
console.writeline(x)
Next
You should be able to see that in line 1 the programmer has misspelt the word to . This code won't work
at all.
Run-time error
Sometimes you will have a program that compiles fine, but breaks when you actually run it. For example
this code here:
Dim x as integer = 0
Dim total as integer = 0
While x < 5
total = total + 1
Loop
The programmer has created an infinite loop, and the value of total will head towards infinity, eventually
breaking the program.
Logic (Semantic) error
A logic error is when a program compiles, doesn't crash, but the answers that it gives are incorrect. The
logic, semantics or meaning, conveyed by the code is wrong. Take a look at the next example:
Fawad Khan 0321-6386013

Page 90

Fundamental of programming for Computer Science 9608 Paper 2

1. Dim Price as decimal = 45.99


2.
3. Dim Tax as decimal = 0.20
4.
5.
6.
7. Console.Writeline("Price {{=}} " & Price)
8.
9. Console.Writeline("VAT {{=}} " & Price * Tax)
10.
11. Console.Writeline("Total {{=}} " & Price + Tax)
12.
In the above example you would expect it to print out:

But because there is a logic error on line 6, it prints:

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

Fawad Khan 0321-6386013

Page 91

Fundamental of programming for Computer Science 9608 Paper 2

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.

will never be greater than 5, since line 3 gives

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

Fawad Khan 0321-6386013

Page 92

Fundamental of programming for Computer Science 9608 Paper 2


What error is in the following code, how would you fix it:
1.
2.
3.
4.
5.
6.
7.
8.
9.

Dim names() As String = {"Harry", "Dave", "Princess", "Nicky"}


'print all the names
For x = 1 to 3
Console.Writeline("name " & x & " = " & names(x))
Next

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 .

There is also a potential

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

Fundamental of programming for Computer Science 9608 Paper 2

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:

The reason, as you should already be aware, is that variable

age

is an integer and you are trying

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?")

This will deal with the issue:

Fawad Khan 0321-6386013

Page 94

Fundamental of programming for Computer Science 9608 Paper 2


Letting us know that you're put a string in when it was expecting an integer. The program doesn't crash.

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

Fawad Khan 0321-6386013

Page 95

Fundamental of programming for Computer Science 9608 Paper 2


2.1.3 Corrective maintenance

perform white-box testing by:


o selecting suitable data
o using a trace table
identify any error(s) in the algorithm by using the completed trace table
amend the algorithm if required

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.

Fawad Khan 0321-6386013

Page 96

Fundamental of programming for Computer Science 9608 Paper 2

Example of Corrective maintenance


Philipe is trying different ways of designing the process of entering data into an array.
He declares a variable called ArraySize and sets it to 3.
He declares an array Number[ArraySize].
He then writes the following pseudocode.
Element 1
WHILE Element < ArraySize DO
INPUT Number[Element]
Element Element + 1
ENDWHILE
(a) In the following table trace the effect of entering 24, 57, 12.

Fawad Khan 0321-6386013

Page 97

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 98

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 99

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 100

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 101

Fundamental of programming for Computer Science 9608 Paper 2

2.1.4 Adaptive maintenance


Make amendments to an algorithm and data structure in response to specification changes
Analyse an existing program and make amendments to enhance functionality
o Give learners an algorithm/program they can amend.
o For example:
o A program that reads in 20 numbers using a FOR loop could be amended so it reads in
numbers until some terminal value.
o The following bubble sort algorithm could be improved:
o FOR value1 = 1 to (n-1)
o FOR value2 = 1 to (n-1)
o COMPARE List[value1] with List[value2]
o IF greater THEN swap elements
o ENDFOR
o ENDFOR
Adaptive maintenance is necessary when conditions change from those that existed when the original
system was created. This may be because of a change in the law (tax rates may change, for example) or
the hardware may be changed, so that changes need to be made to the software for it to remain
functional.

Fawad Khan 0321-6386013

Page 102

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 103

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 104

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 105

Fundamental of programming for Computer Science 9608 Paper 2

Difference between Recursion and Iteration

ITERATIONS

RECURSION
Recursive function is a function that is partially

Iterative Instructions are loop based

defined by itself

repetitions of a process

Recursion Uses selection structure

Iteration uses repetition structure

Recursion terminates when a base case is

Iteration terminates when the loop-

recognized

condition fails

Recursion is usually slower then iteration due to

Iteration does not use stack so it's faster

overhead of maintaining stack

than recursion

Recursion uses more memory than iteration

Iteration consume less memory

Infinite recursion can crash the system

Recursion makes code smaller

Fawad Khan 0321-6386013

infinite looping uses CPU


cycles repeatedly
Iteration makes code longer

Page 106

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

Page 107

Fundamental of programming for Computer Science 9608 Paper 2

It looks very simple and elegant. But how does it work?

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:

Fawad Khan 0321-6386013

Page 108

Fundamental of programming for Computer Science 9608 Paper 2

Function call n Return Line


1
4
All is going well so far until we get to line 3. Now what do we do? We'll soon have two values of n, one for
Function call 1 and one for Function call 2. Using the trace table as a stack (with the bottom of the stack at
the top and the top of the stack at the bottom) we'll save all the data about the function call including its
value of n and make note of what line we need to return to when we have finished with factorial(3).
Function call n Return Line
1
43
2
3
We now have a similar situation to before, let's store the return address and go to factorial(2)
Function call
1
2
3

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

Return Line Return Value


3
3
3
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

Return Line Return Value


3
3
3
2
1

Fawad Khan 0321-6386013

Page 109

Fundamental of programming for Computer Science 9608 Paper 2

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

Return Line Return Value


3
3
6
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.

Fawad Khan 0321-6386013

Page 110

Fundamental of programming for Computer Science 9608 Paper 2

Exam Style Question

Fawad Khan 0321-6386013

Page 111

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 112

Fundamental of programming for Computer Science 9608 Paper 2

Programming Concepts: Object-oriented


programming (OOP)
Object oriented programming is a type of programming paradigm based around programming classes and
instances of classes calledobjects. These can be objects that appear on the screen (e.g., pictures, textboxes,
etc.) or are part of the programming (e.g. actors, connections, particles, etc.).

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

Let's take a look at the following example:


class car
private maxSpeed as integer
public fuel as integer
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)
console.writeline("pumping gas!")
fuel = fuel + x
end sub
public function getFuel() as integer
return fuel
end function
public sub drive()
fuel = fuel - 1
end sub
end class
Fawad Khan 0321-6386013

Page 113

Fundamental of programming for Computer Science 9608 Paper 2

You can see that the class is called

two attributes:
four methods
o
o

car

and it has:

maxSpeed, fuel

three procedures: setSpeed,


one function: getSpeed

refuel, drive

Remember this is a class and therefore only a template, we need to 'create' it


using an object
Attributes
These store information about the object. In the example above we store the
fuel and maxSpeed. The attributes are attached to the classes, and if there
are several instances (objects) of the classes then each will store its own
version of these variables. Note that instead of the usual dim, there is the
word private or public, we'll cover that in the encapsulation section.
Methods

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

Fundamental of programming for Computer Science 9608 Paper 2

attributes), you can also allow for sub routines such as

drive()

and

refuel ,

which are attached to each class.


Exercise: Object Orientation Intro

What is the difference between a class and an object?


Answer :

A class is a template which cannot be executed

An object is an instance of a class which can be executed

one class can be used to make many objects

What are the main components of a class?


Answer :
methods and attributes

What is the difference between a structure and a class


Answer :
structures don't have methods

Fawad Khan 0321-6386013

Page 115

Fundamental of programming for Computer Science 9608 Paper 2

OO - PIIE
When talking about OOP you must remember the following:

Where:

00 = Object Orientation and

PIIE = Polymorphism / Inheritance / Instantiation / Encapsulation

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())

Fawad Khan 0321-6386013

Page 116

Fundamental of programming for Computer Science 9608 Paper 2


This would output the following:

Exercise: Instantiating a car


Write your own instantiation for a beetle car:
Answer :
dim beetle as new car 'instantiation

What would the following output:


dim ka as new car
dim montego as new car
ka.refuel(10) 'assuming fuel starts at 0
montego.refuel(50) 'assuming fuel starts at 0
montego.drive()
montego.drive()
for x = 0 to 10
montego.drive()
next
ka.refuel(10)
console.writeline("ka: " & ka.getFuel())
console.writeline("montego: " & montego.getFuel())

Fawad Khan 0321-6386013

Page 117

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 118

Fundamental of programming for Computer Science 9608 Paper 2


public function getSpeed() 'declaring an interface (a function as we are returning
a value)
return maxSpeed
end function
Because this method is public we can call it through: polo.getSpeed(100) . And because getSpeed is
declared inside the car object, it can have access to all the private attributes and methods.
In general attributes should always be declared as private and only accessible through interfaces, using
a setX command to give the private variable X a new value, and using the getX command to return the value of
X. You should never directly access X!

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!

Write an interface to set the colour


Answer :
public sub setColour(byVal c as string) 'declaring an interface, make sure it's
public!
colour = c
end sub

Write an interface to return the colour

Answer :
public function getColour() 'it must be a function to return
a value
return colour
end function

Fawad Khan 0321-6386013

Page 119

Fundamental of programming for Computer Science 9608 Paper 2


Create an actor class with the following:

attributes: health, dexterity, x, y, strength

methods: walkforward(), eat(), gethit(), displaystats(), setHealth(p), setLocation(px,py)

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

Fundamental of programming for Computer Science 9608 Paper 2

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

Public Sub gethit()


health = health - 10
Console.WriteLine("Argh!")
End Sub

Public Sub displaystats()


Console.WriteLine("Character :" & name)
Console.WriteLine("Health :" & health)
Console.WriteLine("Location :" & x & ", " & y)
End Sub

Public Sub setHealth(ByVal p)


health = p
End Sub

Public Sub setLocation(ByVal px, ByVal py)


x = px
y = py
End Sub

Fawad Khan 0321-6386013

Page 121

Fundamental of programming for Computer Science 9608 Paper 2

76.
77.
78.
79.End Class
80.

For the actor class declared above instantiate:

Wizard called Barry with 100 Health starting at 4,5


Orc called Herbert with 35 Health starting at 20,2, then report on his status

Answer :
dim wizard as new actor
name
dim orc as new actor

'it doesn't have to be named wizard, it could have another


'it doesn't have to be named orc, it could have another name

wizard.setName("Barry") 'remember to use your get and set routines!


wizard.setHealth(100)
wizard.setLocation(4,5)
orc.setName("Herbert")
orc.setHealth(35)
orc.setLocation(20,2)
orc.displaystats()

Fawad Khan 0321-6386013

Page 122

Fundamental of programming for Computer Science 9608 Paper 2


Inheritance

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

Fawad Khan 0321-6386013

Page 123

Fundamental of programming for Computer Science 9608 Paper 2


This seems like a very long and tedious task rewriting all the same code again. You're right! It would be far
better if we only had to declare all the new stuff we wanted to add. OOP allows for inheritance, where a
new class can inherit the attributes and methods of a parent class:
class electricCar
inherits car 'declares what attributes and methods you are inheriting
private numBatteries as integer 'added
public sub setnumBatteries(byVal n as integer) 'interface
numBatteries = n
end sub
public function getnumBatteries() 'interface
return numBatteries
end sub
end class
This means that everything that car declared is now accessible from electricCar, as well as the new
numBatteries attribute and methods. Let's instantiate this example and see what's possible
dim gwiz as new electricCar
gwiz.setnumBatteries(6) 'from electricCar
gwiz.setSpeed(60)
'from car
gwiz.drive()
'from car
By using inheritance it makes creating new classes very quick and easy. It also allows for a modular
approach to creating classes, where you might never use the base class at all, but only as a means of
creating other child classes.
Rather than having to rewrite the same functionality for similar objects, OOP allows you to reuse attributes
and methods fromparent classes.

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

Fundamental of programming for Computer Science 9608 Paper 2

public function getnumSeats() 'interface get


return numSeats
end function
public sub setcolourSeats(byVal c as string) 'interface
set
colourSeats = c
end sub
public function getcolourSeats() 'interface get
return colourSeats
end function
end class
What are the benefits of using inheritance?
Answer :
Creating new classes from parent classes is very quick and easy. It allows for a modular approach to creating
classes, where you might never use the base class at all.

Inheritence diagrams

Fawad Khan 0321-6386013

Page 125

Fundamental of programming for Computer Science 9608 Paper 2


inheritance diagram of vehicles, all sharing attributes and functions from the parent class 'Vehicle'.

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.

Exercise: Inheritance Diagrams

Answer :
vehicle

Draw an inheritance diagram for the following classes:


motor bikes, bikes, vehicles, pedal bikes, trikes.

Fawad Khan 0321-6386013

Page 126

Fundamental of programming for Computer Science 9608 Paper 2

Draw an inheritance diagram for the following classes:


Monster, Character, Dragon, Hero, Orc

Fawad Khan 0321-6386013

Page 127

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 128

Fundamental of programming for Computer Science 9608 Paper 2

Programming Concepts: Abstract data types and data


structures
Abstract(/bstrkt/) - Apart from practice or reality; not concrete; ideal; vague; theoretical; impersonal
In Computer Science an abstract data type (ADT) is a mathematical model for a certain data types or
structures. This doesn't mean that the ADTs can't be programmed, but that we must first understand
them mathematically before we can implement them. ADTs are generally complex things that you have
functions and procedures to interface with.
Dynamic(/danmk/) - Able to change and to adapt, happening at runtime instead of at compile time
Several of the ADTs we are going to look at will be 'dynamic', this means that they can change in size at
run time, taking up more or less memory depending on the what is needed

Fawad Khan 0321-6386013

Page 129

Fundamental of programming for Computer Science 9608 Paper 2

Programming Concepts: Stacks


A stack is an ADT that might involve a dynamic or static implementation. A stack is a last-in-firstout (LIFO) or first-in-last-out (FILO) ADT. Implementations should include two
operations, pushing and popping, and a pointer to the top of the stack.
A real life example is a stack of books you might have on your desk:

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)

Let's take a look at a computer implementation of a stack:

Pushing: Adds a new specified item to the top of the stack

Popping: Removes the item from the top of the stack.

Fawad Khan 0321-6386013

Page 130

Fundamental of programming for Computer Science 9608 Paper 2


Stacks have several uses:

Reversing queues (as seen above with the Alphabetised names)

Performing Reverse Polish Calculations (see ....)

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

Fawad Khan 0321-6386013

Page 131

Fundamental of programming for Computer Science 9608 Paper 2

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

Describe the Stack data type:


Answer :
A stack is a First In Last Out or Last In First Out data type

Give two uses for a Stack in a computer:


Answer :

Reversing queues (as seen above with the Alphabetised names)

Performing Reverse Polish Calculations (see ....)

Holding return addresses of recursive function calls

Fawad Khan 0321-6386013

Page 132

Fundamental of programming for Computer Science 9608 Paper 2

Dim myStack(10) as string


Dim ToS as integer = 0 'this is our pointer
Dim item as string

While item <> #


Console.writeline(please insert item & ToS &
into the stack: )
item = Console.readline()
myStack(ToS) = item
ToS = ToS + 1
End While

For x = ToS to 0 step -1


Console.writeline(Stack item: & x & =
myStack(x) )
Next

&

console.readline()

Fawad Khan 0321-6386013

Page 133

Fundamental of programming for Computer Science 9608 Paper 2

Programming Concepts: Queues


A queue is a first-in first-out (FIFO) abstract data type that is heavily used in computing. Uses for queues
involve anything where you want things to happen in the order that they were called, but where the computer
can't keep up to speed. For example:

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).

Fawad Khan 0321-6386013

Page 134

Fundamental of programming for Computer Science 9608 Paper 2

Fawad Khan 0321-6386013

Page 135

Fundamental of programming for Computer Science 9608 Paper 2

Tree traversal algorithms for a binary tree

Exercise: Unordered Binary Trees


For the following tree note the root, leafs and the left sub tree

Answer :

Root = 5

Left subtree = 2, 1, 4, 3

Leafs = 1, 3, 7, 9

Fawad Khan 0321-6386013

Page 136

Fundamental of programming for Computer Science 9608 Paper 2

Exercise: Ordered Binary Trees


Create a binary tree for the following data input:
5, 2, 6, 8, 4, 1, 9, 7, 3
Answer :

Create a binary tree for the following major city input:


Monaco, Paris, Vatican, Rome, Norwich, Lewisham, New York, Partington

Fawad Khan 0321-6386013

Page 137

Fundamental of programming for Computer Science 9608 Paper 2

Tree traversal algorithms for a binary tree

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)

Fawad Khan 0321-6386013

Page 138

Fundamental of programming for Computer Science 9608 Paper 2


Output(TreeNode.value)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
end sub
This can be summed up as
1. Traverse to left subtree
2. Visit root node (generally output this)
3. Traverse to right subtree
And outputs the following: A, B, C, D, E, F, G, H, I
For sorted binary trees it will output the nodes in order (alphabetical above). Watch out though, sometimes they
might give you unordered binary trees to try and trick you!

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

Fawad Khan 0321-6386013

Page 139

Fundamental of programming for Computer Science 9608 Paper 2

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:

Fawad Khan 0321-6386013

Page 140

Fundamental of programming for Computer Science 9608 Paper 2

NOTE: They may try to trick you using one the following ways:

Right traversal is before left traversal

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.

Exercise: Binary Tree Traversal

Answer :

Pre-order traversal: GEBDFKMR

In-order traversal: BDEFGKMR

Fawad Khan 0321-6386013

Page 141

Fundamental of programming for Computer Science 9608 Paper 2

Post-order traversal: DBFERMKG

What does the following code describe:


sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
Output(TreeNode.value)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
end sub
Answer :
In-Order traversal because the output is in the centre and the left node is traversed before the right node.

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.

Fawad Khan 0321-6386013

Page 142

Fundamental of programming for Computer Science 9608 Paper 2

Answer :

Pre-order traversal: 7,5,4,2,3,8,9,1

In-order traversal: 4,2,5,3,7,9,8,1

Post-order traversal: 2,4,3,5,9,1,8,7

Fawad Khan 0321-6386013

Page 143

Fundamental of programming for Computer Science 9608 Paper 2

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.

Bubble sort works as follows:


1. Compare adjacent elements. If the first is greater than the second, swap them.
2. Repeat this for each pair of adjacent elements, starting with the first two and ending with last two. At this
point the last element should be the greatest.
3. Repeat the steps for all elements except the last one.
4. Keep the repeating for one fewer element each time until there are no more pairs to compare.

Programming code

Fawad Khan 0321-6386013

Page 144

Fundamental of programming for Computer Science 9608 Paper 2


How it works?
The initial values stored in the array are as follows:
10

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

Fawad Khan 0321-6386013

15

25

30

Page 145

Fundamental of programming for Computer Science 9608 Paper 2

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

Fawad Khan 0321-6386013

15

25

30

Page 146

Fundamental of programming for Computer Science 9608 Paper 2


At this point, the inner loop is completed and the second largest value in array has moved in the second last
element. It means that the position of second largest values is now finalized. Now the control moves to the
beginning of outer loop and the value of i becomes 2.

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:

Fawad Khan 0321-6386013

Page 147

Fundamental of programming for Computer Science 9608 Paper 2

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.

Fawad Khan 0321-6386013

Page 148

Fundamental of programming for Computer Science 9608 Paper 2

Binary Sort

Fawad Khan 0321-6386013

Page 149

S-ar putea să vă placă și